Ask the user for a sentence (one string). Take each word and reverse the order o
ID: 659746 • Letter: A
Question
Ask the user for a sentence (one string). Take each word and reverse the order of its letters, keeping the order of the words unchanged. Output the modified sentence (one string). Assume that the sentence is properly capitalized and ends with a period, and do the same to the output. You may assume that the input does not contain digits, punctuation, or extraneous spaces.
Example:
Explanation / Answer
import java.util.Scanner; public class ReverseWord { public String reverseWords(String s) { if (s == null) return null; else { String reverseWord = ""; String[] words = s.split(" "); if (words.length > 0){ for(int i = words.length - 1; i >= 0; i--){ if(!words[i].isEmpty()) { if(i == words.length - 1){ reverseWord = words[i]; } else{ reverseWord += (" " + words[i]); } } } } return reverseWord; } } public static void main(String[] args) { // TODO Auto-generated method stub Scanner scanner = new Scanner(System.in); String inputString; String reverseString; ReverseWord reverseWord = new ReverseWord(); while(!"".equals(inputString = scanner.nextLine())) { reverseString = reverseWord.reverseWords(inputString); System.out.println(reverseString); } reverseString = reverseWord.reverseWords(inputString); System.out.println(reverseString); } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.