0

为什么我的代码将旧词与新词组合在一起?输入是“banana” 输出“banana” 新输入“dog” 输出“bananadgo”?

public static void main(String [] args)
{
    Scanner keyboard = new Scanner(System.in);
    String word, afc, newWord;
    String s="";

    do
    {
        word=keyboard.next().toLowerCase();
        int i =word.length()-1;
        char firstLetter=word.charAt(0);
        afc=word.substring(1);
        newWord= afc+firstLetter;

        for( ; i>=0 ; )
        {
            s += newWord.charAt(i--);
        } 
        System.out.println(word + "," + s);

        if (s.equals(word))
            System.out.println("Words are equal.");
        else
            System.out.println("Words are not equal.");
    }
    while (!(word.equals("quit")));

}
4

2 回答 2

1

您没有s在循环开始时清除变量。

应该

    Scanner keyboard = new Scanner(System.in);
    String word, afc, newWord;    

    do
    {
        String s=""; 
        ...
于 2013-03-09T12:08:04.443 回答
0

试试这个

public static void main(String [] args)
{
    Scanner keyboard = new Scanner(System.in);
    String word, afc, newWord;
    String s="";

    do
    {
        s = "";
        word=keyboard.next().toLowerCase();
        int i =word.length()-1;
        char firstLetter=word.charAt(0);
        afc=word.substring(1);
        newWord= afc+firstLetter;

        for( ; i>=0 ; )
        {
            s += newWord.charAt(i--);
        } 
        System.out.println(word + "," + s);

        if (s.equals(word))
            System.out.println("Words are equal.");
        else
            System.out.println("Words are not equal.");
    }
    while (!(word.equals("quit")));

}
于 2013-03-09T12:03:53.060 回答