下面的程序应该这样做:
当用户输入时: The quick brown fox. Jumps over. The lazy dog.
它应该输出:God yzal eth. Revo spmuj. Xof nworb kciuq eht.
但是当用户输入时:The quick brown fox. Jumps over. The lazy dog.
它输出:xof nworb kciuq ehT. revo spmuJ . god yzal ehT .
所以这是我的代码:
import java.util.*;
public class Reverse {
public static void main( String args[] ) {
String paragraph;
Scanner input = new Scanner (System.in);
System.out.print("Enter a paragraph: ");
paragraph = input.nextLine();
paragraph = paragraph.trim();
StringTokenizer tokens = new StringTokenizer(paragraph, ".");
while (tokens.hasMoreTokens()){
String ss = tokens.nextToken();
for (int i = ss.length() - 1; i>=0; i--) {
System.out.print(ss.charAt(i));
}
System.out.print(". ");
}
System.out.println();
}
}
我也想到了这个:
import java.util.*;
public class Reverse{
public static void main(String[] args) {
String paragraph;
Scanner input = new Scanner (System.in);
System.out.print("Enter a paragraph: ");
paragraph = input.nextLine();
paragraph = paragraph.trim();
StringTokenizer parWordTokenizer = null;
StringTokenizer parDotTokenizer = null;
int numParDotTokens = 0;
int numParWordTokens = 0;
parDotTokenizer = new StringTokenizer (paragraph, ".");
parWordTokenizer = new StringTokenizer (paragraph);
numParDotTokens = parDotTokenizer.countTokens();
numParWordTokens = parWordTokenizer.countTokens();
String[] sentences = new String[numParDotTokens];
String[] words = new String[numParWordTokens];
String[] characters = new String[5];
for (int i=0; i<numParDotTokens; i++) {
sentences[i] = parDotTokenizer.nextToken();
System.out.print("S: "+sentences[i]+"\n");
parWordTokenizer = new StringTokenizer (sentences[i]);
numParWordTokens = parWordTokenizer.countTokens();
while (parDotTokenizer.hasMoreTokens()){
String ss = parDotTokenizer.nextToken();
for (int k = ss.length() - 1; k>=0; k--) {
System.out.print(ss.charAt(k));
}
System.out.print(". ");
}
for (int j=0; j<numParWordTokens; j++) {
words[j] = parWordTokenizer.nextToken();
System.out.print("W: "+words[j]+"\n");
while (parWordTokenizer.hasMoreTokens()){
String ss = parWordTokenizer.nextToken();
for (int k = ss.length() - 1; k>=0; k--) {
System.out.print(ss.charAt(k));
}
System.out.print(". ");
}
}
}
} }
但 revo spmuJ . god yzal ehT . kciuq. nworb. xof. Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at ScrambleParagraph.main(Reverse.java:40)
请帮我解决它。几天来我一直在考虑正确的实现,但我是 Java 新手,所以至少现在我做不到。非常感谢你!