Java Palindrome赋值 - 布尔值总是返回False值

时间:2014-09-25 21:52:41

标签: java boolean palindrome

大家。我遇到了Java编程课的作业问题,希望你对此有所了解。

方法 pA 的分配是仅使用 String Character 方法创建方法。因此,我编写了以下方法,当我尝试调用方法 pA 时,它会自动返回false值。我想我的for循环可能有问题,但我不确定,我想我会在这里问你要说些什么。

提前感谢您的时间。

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in); //Creates Scanner object to take user input

    String pal; //String to contain user input

    boolean test = false; //boolean to test if user input is a palindrome.

    System.out.println("This program determines if your input is a palindrome!");
    System.out.println("Please enter your input to see if it's a palindrome.");
            pal = keyboard.nextLine();

    pA(pal, test);
    if (test == true)
    {
        System.out.println("Congratulations! You have a palindrome!");
    }
    else if (test == false)
    {
            System.out.println("Unfortunately, you do not have a palindrome.");
    }

}

public static boolean pA(String pal, boolean test) //Part A of Assignment 7.
{
    int l = pal.length(); //integer to contain length of string
    int i; //Loop control variable
    test = false;

    for (i = 0; i < l/2; i++) //for loop that tests to see if input is a palindrome.
    {
        if (pal.charAt(i) == pal.charAt(l-i-1)) //Compares character at point i with respective character at the other end of the string.
        {   
            test = true; //Sets boolean variable to true if the if statement yields true.
        } else 
            test = false; //Otherwise, a false value is returned.
             break;
    }
    return test; //Return statement for boolean variable
} //End pA

从这里开始,当我尝试运行程序时,使用输入“tubbut”时会收到以下消息:

运行:

此程序确定您的输入是否是回文!

请输入您的输入以查看它是否是回文。

tubbut

不幸的是,你没有回文。

建立成功(总时间:2秒)

1 个答案:

答案 0 :(得分:4)

您忽略了调用pA方法的结果,因此test中的main变量未更改。此外,没有理由将test传递给pA,因为pA只有一个值的副本。

主要是尝试

test = pA(pal);

pA中,删除test参数;你可以把它变成一个局部变量。

public static boolean pA(String pal) //Part A of Assignment 7.
{
   int l = pal.length(); //integer to contain length of string
   int i; //Loop control variable
   boolean test = false;  // *** Now it's a local variable
   // Rest of method is here.
}

此外,在main中,test已经boolean,因此您无需将其与truefalse进行比较。你可以替换

if (test == true)
{
    System.out.println("Congratulations! You have a palindrome!");
}
else if (test == false)
{
    System.out.println("Unfortunately, you do not have a palindrome.");
}

if (test)
{
    System.out.println("Congratulations! You have a palindrome!");
}
else
{
    System.out.println("Unfortunately, you do not have a palindrome.");
}