Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
For loop Java回文总是返回true_For Loop_Palindrome - Fatal编程技术网

For loop Java回文总是返回true

For loop Java回文总是返回true,for-loop,palindrome,For Loop,Palindrome,我试图使用for循环创建一个带有JOptionPane的回文java程序,但不管输入是否真的是回文,它总是返回true。如果你们知道下面的代码有什么问题,请大家帮忙,谢谢 public class program { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here J

我试图使用for循环创建一个带有JOptionPane的回文java程序,但不管输入是否真的是回文,它总是返回true。如果你们知道下面的代码有什么问题,请大家帮忙,谢谢

    public class program {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here
    JOptionPane.showMessageDialog(null, "Welcome to The Palindrome!", "Hello", JOptionPane.INFORMATION_MESSAGE);
    String str = JOptionPane.showInputDialog("Please input a string");
    int len = str.length();
    int j = len - 1;
    int i = 0;
    boolean result;
    for(i = 0; i <= (len - 1)/2; i++);
    {
        if(str.charAt(i) != str.charAt(j)) 
            result = false;       
        j--;
    }
    if(result = true)
        JOptionPane.showMessageDialog(null, str + " is a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
    if(result = false)
        JOptionPane.showMessageDialog(null, str + " is not a palindrome.", "ByeBye", JOptionPane.INFORMATION_MESSAGE);
        
}
公共类程序{
/**
*@param指定命令行参数
*/
公共静态void main(字符串[]args){
//此处的TODO代码应用程序逻辑
showMessageDialog(null,“欢迎使用回文!”,“您好”,JOptionPane.INFORMATION_MESSAGE);
String str=JOptionPane.showInputDialog(“请输入字符串”);
int len=str.length();
int j=len-1;
int i=0;
布尔结果;

对于(i=0;i当您检查
result
的值时,您使用的是
=
,它将该值分配给
result
变量,并始终计算为true

要更正代码,可以删除等号,也可以使用
result==true
(通常使用前者,因为前者更简洁)


但是,这可能会导致错误,因为您没有初始化result的值。我建议将其值设置为
true
作为默认值。

而不是使用传统方法检查回文,只需使用智能方法。开始吧

boolean result = str.equalsIgnoreCase(new StringBuffer(str).reverse().toString());