Please use Java. Use a stack to reverse the words of a sentence. Keep reading wo
ID: 3858897 • Letter: P
Question
Please use Java.
Use a stack to reverse the words of a sentence. Keep reading words until you have a word that ends in a period, adding them onto a stack. When you have a word with a period, pop the words off and print them. Stop when there are no more words in the input. For example, you should turn the input:
Mary had a little lamb. Its fleece was white as snow.
into
Lamb little a had mary. Snow as white was fleece its.
Pay attention to capitalization and placement of the period.
Could you help me to complete the following code?
import java.util.*;
public class stringRev {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
Scanner in = new Scanner( System.in );
System.out.println("Enter a sentence to reverse: ");
while (in.hasNext()) {
String token = in.next();
stack.push( token );
}
String reverse = "";
while (stack.size() > 0) {
reverse = reverse + " " + stack.pop();
}
System.out.println( reverse );
}
}
Explanation / Answer
HI below is your working code. I have actually divided the code into two functions - one main and one to print reverse of each line. If you want to have both in same function i.e. main.. Let me know in comments I'll update the answer...
import java.util.*;
public class stringRev {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str;
System.out.println("Enter the String to reverse: ");
str = scan.nextLine();
String[] line;
line = str.split("\.");
System.out.println("The reversed String is: ");
for (int i = 0; i < line.length; i++) {
Stack<String> Stack1 = new Stack<String>();
String[] temp1;
String delimit1 = " ";
temp1 = line[i].split(delimit1);
for (int j = 0; j < temp1.length; j++) {
if(temp1[j].length() > 0) {
Stack1.push(temp1[j]);
}
}
int size = Stack1.size();
if(!Stack1.empty()) {
String firstWord = Stack1.pop();
firstWord = Character.toUpperCase(firstWord.charAt(0))+ firstWord.substring(1, firstWord.length());
System.out.print(firstWord);
System.out.print(" ");
}
for (int j = 1; j < size - 1; j++) {
System.out.print(Stack1.pop());
System.out.print(" ");
}
if(!Stack1.empty()) {
String lastWord = Stack1.pop();
lastWord = Character.toLowerCase(lastWord.charAt(0))+ lastWord.substring(1, lastWord.length());
System.out.print(lastWord);
}
System.out.print(".");
System.out.print(" ");
}
}
}
Sample Run: -
Enter the String to reverse:
Use a stack to reverse the words of a sentence. Keep reading words until you have a word that ends in a period adding them onto a stack.
The reversed String is:
Sentence a of words the reverse to stack a use. Stack a onto them adding period a in ends that word a have you until words reading keep.