0

我需要编写一个程序,从用户那里获取一个字符串并测试它是否是回文。这必须通过嵌套循环来完成:我无法编写返回答案的方法。我还必须继续接受字符串输入并对其进行测试,直到用户输入一个空行,此时程序打印“再见”并终止。我遇到的问题是让程序在两个可能的输入点之后接受输入(是回文,不是),然后在循环中使用新输入,并每次打印适当的行。

输出应该是这样的:

输入字符串:转子

转子是回文。

输入一个字符串:妈咪

木乃伊不是回文。

输入一个字符串:

空行读取。再见。

这是我到目前为止所拥有的,它测试每个输入并返回正确的语句,但是当输入为空时它什么也不做:

System.out.print("Enter a string: ");
String input = in.next();
if (input.length() > 0) {
     int x = 0;
     int y = input.length()-1;
     while (x < y) {
          if (input.charAt(x) == input.charAt(y)) {
               x++;
               y--;
          }
          else {
               System.out.println(input + " is NOT a palindrome.");
               System.out.println("Enter a string: ");
               input = in.next();
          }
          System.out.println(input + " is a palindrome.");
          System.out.println("Enter a string: ");
          input = in.next();
     }
}
else {
     System.out.print("Empty line read - Goodbye!");
}

有什么想法吗?这是作业,顺便说一句,所以我不是在寻找答案,而是寻找线索,或者我需要看的东西。

4

1 回答 1

2

OK, Since it's your homework, I'll just give you a brief description about how you can proceed: -

  • Since you need to continously take user input, so probably you would be needing some kind of loop, that can continue until a condition is reached (You can think, what loop constrct will go here)

  • Secondly, you need to ask user when he want to quit, so you need to specify a exit condition..

  • Third, for checking for palindrome, you need to check a string with it's reverse..

  • Since you have to use nested loop, you can use length of the string entered, in your loop condition.. Remember, you just need to loop till half the length. Why, you need to find out.. then, compare first character with last, then 2nd character with 2nd last.. until characters are matching.. You need to find out when you will exit the loop..

I think this much information will get you started..

Also one more thing.. May be you are restricted with the use of any method, but it is absolutely bad idea and ugly design to do everything in main().. In fact any of your method should not do more than one task.. And especially your main() method should ideally be just 4 - 5 lines long..

When coding a method, if you think this part is something different, move it outside to another method, and invoke it.. This is the way you should code..

于 2012-10-02T21:06:01.283 回答