【问题标题】:Why won't while loops find a palindrome in java?为什么while循环在java中找不到回文?
【发布时间】:2017-12-23 18:11:06
【问题描述】:

我不知道我是否只是做错了,但是使用 eclipse 运行它并输入一个单词但它不会返回任何内容。我不擅长编码,所以请帮忙。

import cs1.Keyboard;
public class Palindrome 
{
    public static void main (String[]args)
    {
        System.out.print("Enter a word: ");
        String w = Keyboard.readString();
        int a = 0;
        char n = w.charAt(a);
        char j = w.charAt(w.length()-1);
        while(a < j);
        {
            if (j!=n)
                System.out.println("This word isnt a palindrome... try     again.");
            if (j==n)
            {
                j--;
                a++;
            }
                System.out.println("This is a palindrome!");
        }
    }
}

【问题讨论】:

  • 这段代码有很多错误。我建议回顾一下如何在 java 中编写方法。
  • 即使考虑到Keyboard 类正确地返回了一个字符串,你的while 循环后面还有一个;。删除它。然后使用调试器来测试你的逻辑
  • 所以你忽略了关于空while循环的警告?我确信 Eclipse 能够告诉你这是一个坏主意。

标签: java eclipse


【解决方案1】:

试着写

char j = w.charAt(w.length() - a);

并且,当在 while 循环中增加 a 时,更新索引

n = w.charAt(a);
j = w.charAt(w.length()-1);

另外,确保 Keyboard.readString() 返回一个字符串。尝试使用扫描仪。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-12
    • 2012-11-07
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多