2011-03-07 59 views
0

以下代碼要求輸入兩次數字。用戶輸入提問兩次

public class Palindrome { 

    public static void main(String[] args) { 
    boolean x; 
    boolean display; 

    x = check(); 
    display = display(); 
    } 

    private static int getUserInput() { 
    int inputNumber = 0; 
    String answer = JOptionPane.showInputDialog(null, "Please enter a five digit number","Enter a number"); 
    inputNumber = Integer.parseInt(answer); 
    return inputNumber; 
    } 

    private static boolean check(){ 
    int inputNumber = getUserInput(); 
    int number = inputNumber; 
    int[] myArray = new int[5]; 

    for (int i = 0; i < myArray.length; i++) { 
     myArray[i] = (int) (number /(Math.pow(10,i)) % 10); 
    } 

    if(myArray[0] == myArray[4] && myArray[1] == myArray[3]) 
     return true; 
    else 
     return false; 
    } 

    public static boolean display(){ 
    if (check() == true) { 
     JOptionPane.showMessageDialog(null, "This number is a Palindrome", 
      "Excellent!", 
      JOptionPane.INFORMATION_MESSAGE); 
    } else 
     JOptionPane.showMessageDialog(null, 
      "Number is not a Palindrome!", 
      "Sorry", 
      JOptionPane.ERROR_MESSAGE); 
     return false; 
    } 
} 

我希望它只問一次。

感謝

+0

並且在一個不相關的註釋中,你在'display'方法裏面'else'塊丟失了一個大括號 – 2011-03-07 17:26:01

回答

1

您是第一次調用檢查()的主要功能:

x = check(); 

,然後再次顯示功能

if(check() == true) 

如果你只需要調用從主顯示屏,你的代碼沒事的。

+0

我知道這很簡單,謝謝 – Mike 2011-03-07 20:30:27

4

這是因爲你在頂層(它要求輸入)調用check(),但你打電話check()再次作爲display()一部分。因此,第一個輸入被完全忽略(試一下,只有第二個輸入會影響消息)。您的通話樹是這個樣子:

main() 
|- check() 
| |- getUserInput(...) 
| | |- *(show input dialog)* 
| 
|-display() 
| |- check() 
| | |- getUserInput(...) 
| | | |- *(show input dialog)* 
| | 
| |- (show message dialog) 

我懷疑你的意思做的是以前執行的結果傳遞到display()作爲一個變量,而不是再次調用方法。這可能是這個樣子:

public static void main(String[] args) { 
    boolean x = check(); // No real need to declare the variable separately 
    boolean display = display(x); 
} 

... 

public static boolean display(boolean check) { 
    if (check) { // P.S. no need to explicitly use the "== true" 
     ... 
    } else 
    ... 
} 

或者,你可以下降調用check()main只有使從display方法之一。在我看來,將「輸入」和「顯示輸出」方法分爲兩個單獨的方法是更好的編程實踐。也處理輸入的輸出方法是非平凡系統中的噩夢。

2

您的display()方法第二次調用check()

1

您已撥打check()方法兩次。每次顯示輸入對話框。