while循环在reentry上的表现不同(java)

时间:2014-07-13 15:59:01

标签: java

我有一个任务,我必须制作一个程序,读取输入并评估它是否是回文直到用户终止。我遇到了while循环的问题。它在第一次输入时就像它应该的那样,但是当它重新进入循环时,它总是说它不是一个回文,即使是它。

Scanner in;
    in = new Scanner (System.in);

    String original = "";       //variable for user input
    String original2 = "";      //variable to help make input case insensitive
    String reverse = "";        //variable to compare word in reverse
    int length;                 //variable used to 
    int i;                      //variable used in for loop
    //String response = "";

    System.out.println("Enter a word to check if it is a palindrome!");

    original = in.nextLine();

    while (!original.equals("n")) 
    {
        length = original.length();

        original2 = original;       //assigning a new variable to hold the input, so as to not change it

        original2 = original.toLowerCase(); //converting input to all lower case using the holder variable 

        for (i = length -1; i >= 0; i--)    //for loop reversing the word to check for palindrome status
        {
            reverse = reverse + original2.charAt(i);
        }

        if (original2.equals(reverse))      //if statement determining output if palindrome is true or not
        {
            System.out.println(original + " is a palindrome");
        }
        else
        {
            System.out.println(original + " is not a palindrome");
        }

        System.out.println("Enter another word or enter 'n' to end");   //allowing to continue
        original = in.nextLine();

    }

System.out.println("thank you!");
    in.close();
}

我最初认为这是缓冲区的问题,但我不再认为这是一个问题。

我真的很感激任何帮助

1 个答案:

答案 0 :(得分:1)

您不会重置reverse,因此反向字符串会不断构建