Monday, January 26, 2015

Here is another simple and basic program for beginners, a very simple logic and algorithm, that can simply reverse a word or a sentence, like for example if i type "all about that bass" obviously the output is "bass that about all". So, just take a look at the code below on how to deal with it;


package teamUndefined;

import java.io.*;

public class ReverseWord {

public static void main(String[] args)throws IOException{

BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));

String _input; String[] _array;
_input = buff.readLine();
_array = _input.split(" ");

/*now i can use the split method to put user input in the array for, for me to easily iterate or access the index  of a words, from the loop below, i initialize the i equal to size of the array, which where i stored the user input, and decremented it*/

for (int i = _array.length; i > 0; i--) {
System.out.print(_array[i-1].concat(" "));
}
}

}

and how about the if we to reverse the a one word, so that means we need to reverse the letters, not the word, so this is my solution for that.

/*we need to initialize the array size first, so no we store the _input size of the user*/

_array = new String[_input.length()];
/*for this loop, i used subString method for me to slice those letters and store it on a array*/

for (int i = 0; i < _array.length; i++) {
        _array[i] = _input.substring(i, i + 1);
}

and by displaying the output, just same method that i used on the first example.








i hope this sample program will help you, specially if you are beginners and new to java.
enjoy :)

0 comments:

Post a Comment