Friday, July 31, 2009

How to write a Java program that reads a phrase from the input and outputs its words in reverse order?

The output should be on a single line terminated by a newline, and should only have the single spaces needed to separate the words. For example, if the input is


Data Structures and Algorithms in Java


the output should be Java in Algorithms and Structures Data


using recursion and the java.util.Scanner class for parsing the input

How to write a Java program that reads a phrase from the input and outputs its words in reverse order?
import java.util.*;


public class HelloWorld {


public static Stack stack=new Stack();


public static void main(String[] args) {


try {


String s="this is java string reverse ";


reverseString(s);


System.out.println("the reversed string value is ");


for(int i=stack.size()-1;i%26gt;=0;i--){


System.out.print(stack.get(i));


}


}


catch (Exception e) {


e.printStackTrace();


}


}


public static void reverseString(String s) throws Exception{


StringTokenizer temp=new StringTokenizer(s);


if(temp.hasMoreTokens()){


String s1=temp.nextToken();


stack.push(s1+" ");


reverseString(s.substring(s1.length()+1)...


}


else{


return;


}


}





}
Reply:Is there a stack function? First in Last out. Then store and retrieve the word.


I know this in Pascal and BASIC and it is a basic structure in computer science.
Reply:Without going into the input piece (which is easy) basically you want to take the input as a String.


Then you can do something like the following:





String input = "whatever I got from the input line";


StringBuffer backwards = new StringBuffer();


for (int x=input.length; x%26gt;0; x--) {


backwards.append(


input.charAt(x));


}


System.out.println(backwards.toString(...


No comments:

Post a Comment