我的do / while循环第二次使我的程序变得混乱

时间:2015-02-12 01:49:55

标签: java java.util.scanner do-while palindrome

我遇到的问题是我输入了一个像" non"我回来了它是一个回文。然后我输入"是"正如我问的那样#34;继续前进?"。它开始在" Type Word:"我打字#34;非"再次。但这次我回来了它不是回文。我认为它与我如何声明我的变量或可能与for循环有关。我无法解决这个问题。任何帮助表示赞赏。

import java.util.*;
public class palindromeTest
{
 public static void main (String [] args)
 {
  Scanner in = new Scanner (System.in);
  String word = "", backword = "", exit = "";
  int length;
  do{
     System.out.print ("Type a Word: ");
     word = in.nextLine();

     length = word.length();

     for (int i = length - 1; i >= 0; i--)
        backword = backword + word.charAt(i);
     if (word.equalsIgnoreCase(backword))
        System.out.println ("This IS a Palindrome.");
     else 
        System.out.println ("This is Not a Palindrome.");

     System.out.println ("Keep Going? /n Yes or No?");
     exit = in.nextLine();
  }while(exit.equalsIgnoreCase ("Yes"));
}//end main
}//end palindromeTest

1 个答案:

答案 0 :(得分:0)

backward的声明移动到循环体中(因此它会在每次迭代时重置),

String word = "", exit = "";
int length;
do {
    String backword = "";

但是,使用StringBuilder进行String连接更好一点,但我会将优化作为练习留给读者。