2015-10-20 81 views
1

我想反覆要求用戶輸入一個整數,但也允許他們取消。我有這樣的:如何獲取有效的整數輸入,但允許用戶輸入空值?

int numSelectedCols = 0; 
boolean validInput = false; 

while(!(numSelectedCols > 0) && !validInput) { 
    try { 
     numSelectedCols = Integer.parseInt(JOptionPane.showInputDialog("Enter number of columns to be selected: ")); 
     validInput = true; 
    } 
    catch (NumberFormatException e) { 
     System.out.println("Please enter an integer value"); 
    } 
} 

它多次要求一個有效的輸入,但是當我按下「取消」按鈕,它依然保持着問。我該如何解決?

謝謝。

回答

0

我想這樣的作品:

while(!validInput) { 
    input = JOptionPane.showInputDialog("Enter number of columns to be selected: "); 
    if(input != null) { 
     try { 
      numSelectedCols = Integer.parseInt(input); 
      if(numSelectedCols > 0) { 
       validInput = true; 
      } 
     } 
     catch (NumberFormatException e) { 
      System.out.println("Please enter an integer value"); 
     } 
    } 
    else { 
     validInput = true; 
    } 
} 
相關問題