这是我作业的解决方案,目的是根据用户输入的句子来反转字符串中的每个单词。我自己完成了这个,但我只是想知道迭代器在这段代码中是如何工作的。我不明白 tempword = ""; 的声明 以及他如何打印出由空格分隔的每个单词。
import java.util.Scanner;
public class StringReverser
{
public static void main(String args[])
{
String sentence;
String word;
String tempWord = "";
Scanner scan = new Scanner(System.in);
Scanner wordScan;
System.out.print("Enter a sentence: ");
sentence = scan.nextLine();
wordScan = new Scanner(sentence);
while(wordScan.hasNext())
{
word = wordScan.next();
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
System.out.print(tempWord + " ");
tempWord = "";
}
System.out.println();
}
}