Answer to Question #57480 in Java | JSP | JSF for Nancy Rodriguez
Question #57480
Write a program that reads in a sentence from the user and prints it out with each word reversed, but with the words and punctuation in the original order.
Expert's answer
package com.company;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sentence, new_sentence;
new_sentence = "";
String reverse = "";
sentence = reader.readLine();
char[] symbol = {'-', ',', ';', ':', '.', '!', '?', ' ', '(', ')'};
String[] words = sentence.split("[-,;:.!?()\\s]+");
int count_words = words.length;
char[] chars = sentence.toCharArray();
int number_word = 0;
for(int i = 0; i < chars.length; i++){
if(new String(symbol).indexOf(chars[i]) != -1)
new_sentence += chars[i];
else{
if(number_word < count_words) {
new_sentence += new StringBuffer(words[number_word]).reverse().toString();
i = i + (words[number_word].length()-1);
number_word++;
}
}
}
System.out.println(new_sentence);
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sentence, new_sentence;
new_sentence = "";
String reverse = "";
sentence = reader.readLine();
char[] symbol = {'-', ',', ';', ':', '.', '!', '?', ' ', '(', ')'};
String[] words = sentence.split("[-,;:.!?()\\s]+");
int count_words = words.length;
char[] chars = sentence.toCharArray();
int number_word = 0;
for(int i = 0; i < chars.length; i++){
if(new String(symbol).indexOf(chars[i]) != -1)
new_sentence += chars[i];
else{
if(number_word < count_words) {
new_sentence += new StringBuffer(words[number_word]).reverse().toString();
i = i + (words[number_word].length()-1);
number_word++;
}
}
}
System.out.println(new_sentence);
}
}
Need a fast expert's response?
Submit orderand get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Comments
Leave a comment