2014-09-25 53 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