Write a program that reverses a sentence, (Example: input : my name is ; output:
ID: 3741409 • Letter: W
Question
Write a program that reverses a sentence, (Example: input : my name is ; output: is name my ) Here what i've done:
import java.util.*;
import java.lang.*;
public class W4 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = s1.nextLine();
int g = sentence.lastIndexOf(" ");
//should use last index of a space and move it to the front of the sentence//
for(int i =0;i<1234;i--){
String k = sentence.substring(x,g);
System.out.println(k);
}
System.out.println(g);
}
}
Explanation / Answer
W4.java
import java.util.*;
import java.lang.*;
public class W4 {
public static void main(String[] args) {
Scanner s1 = new Scanner(System.in);
System.out.println("Enter a sentence");
String sentence = s1.nextLine();
int g = sentence.lastIndexOf(" ");
while(g != -1) {
System.out.print(sentence.substring(g+1,sentence.length())+" ");
sentence = sentence.substring(0,g);
g = sentence.lastIndexOf(" ");
}
System.out.println(sentence);
}
}
Output:
Enter a sentence
my name is
is name my
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.