2014-09-25 93 views
1

everyone。我在为Java编程课程分配任务时遇到问题,并希望对此有所意见。Java回文分配 - 布尔总是返回False值

对于该方法的分配pA的是创建仅使用字符串字符方法的方法。因此,我编写了以下方法,当我尝试调用方法pA时,它会自动返回一个假值。我想我的循环可能有问题,但因为我不确定,所以我想我会在这里问一下,看你有什么要说的。

在此先感谢您,为您的时间。

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

不幸的是,你没有回文。

BUILD SUCCESSFUL(总时间:2秒)

回答

4

你忽略你的电话到pA方法的结果,所以在maintest变量是不变的。另外,没有理由将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. 
} 

此外,在maintest已经boolean,所以你不需要把它比对truefalse。你可以用

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

这帮助了很多替代

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."); } 

;非常感谢你! – Brian 2014-09-25 22:11:04