这是我的作业的解决方案,目的是根据用户输入的句子来反转字符串中的每个单词。我自己完成了此操作,但我只是想知道迭代器在这段代码中是如何工作的。我不明白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();
    }
}

最佳答案

这一点增加了空间

System.out.print(tempWord + " ");


这一点扭转了它

for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
            tempWord += word.charAt(numLetters);


该位设置为下一个单词

tempWord = "";

10-06 14:05