Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

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

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote