Java Problem 3 For each problem, you should: determine the inputs, outputs, and
ID: 3761293 • Letter: J
Question
Java Problem 3
For each problem, you should:
determine the inputs, outputs, and error conditions
construct an algorithm
code your algorithm in Java
construct a set of test cases and use them to test and fix your program
Problem 3:
Ask the user for a sentence.
Output a sentence containing the same words, but in reverse order.
You may assume that the input sentence contains no punctuation except for a period at the end. The output sentence should be properly capitalized and ended with a period.
java ReverseWords
The quick brown fox jumps over the lazy dog.
RESULT: "Dog lazy the over jumps fox brown quick the."
Explanation / Answer
import java.util.Scanner;
public class ReverseString {
private static Scanner input;
public static void reverse(String s)
{
String s1="";
for (int i=0; i<=s.length()-1; i++)
{
if(s.charAt(i)!=' ')
s1=s1+s.charAt(i);
else {
String ops=revst(s1);
System.out.print(ops+" ");
s1="";
}
if(i==s.length()-1){
String ops=revst(s1);
System.out.print(ops);
}
}
}
public static String revst(String s)
{
String revString = "";
for (int j=s.length()-1; j!=-1; j--)
revString= revString + s.charAt(j);
return revString;
}
public static void main(String[] args)
{
input = new Scanner(System.in);
System.out.println("Please enter a Sentence: ");
String ips = input.nextLine();
System.out.println("Sentence after reversing the words is:");
reverse(ips);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.