此代码应该反转我输入" 123ab 445 Hello"然后,我得到了#46; olleh 544 ba321"作为我的输出。为什么会这样?
import java.util.StringTokenizer;
import java.util.Scanner;
public class LessNaiveEncryption {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Provide an input sentence: ");
String userInput = keyboard.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(userInput, " ", true);
System.out.print("The output sentence is : ");
while (strTokenizer.hasMoreTokens()) {
strTokenizer.nextToken();
}
StringBuilder blob = new StringBuilder(userInput);
blob.reverse();
System.out.println(blob);
System.out.print("\n");
}
}
答案 0 :(得分:0)
您的主要问题是您没有使用StringTokenizer做任何事情。您正在迭代结果,但不会反转它们。将反面放在循环内并打印出结果。
Scanner keyboard = new Scanner(System.in);
System.out.print("Provide an input sentence: ");
String userInput = keyboard.nextLine();
StringTokenizer strTokenizer = new StringTokenizer(userInput, " ", true);
System.out.print("The output sentence is : ");
while (strTokenizer.hasMoreTokens()) {
String str = strTokenizer.nextToken();
StringBuilder blob = new StringBuilder(str);
System.out.print(blob.reverse());
}
System.out.print("\n");
}
答案 1 :(得分:0)
您正在反转整个String,拆分它然后反转每个分割:
String[] split = userInput.split(" ");
String result = "";
for(String s : split){
result += new StringBuilder(s).reverse().append(" ").toString();
}
System.out.println(result);