2013-10-28 14 views
-1

例如,我正在編寫一個採用textinput的程序,並將其轉換爲int。我希望輸入的數字小於或等於5,但大於或等於0(0 < =數字< = 5),我會如何寫這個?如何聲明一個int爲特定值/數

int number; 
    textinput = JOptionPane.showInputDialog("give me a number"); 
    number = Integer.parseInt(textinput); 

我希望用戶0和5之間輸入一個數字,如果他們輸入任何其他號的消息說,號碼是無效的,而且他們再次輸入

編輯:謝謝你的答案,我用while循環和它的工作原理,我只想問現在,我將如何使框彈出窗口說:「錯誤:請輸入一個0到5之間的數字」,然後再次顯示輸入框。

感謝

+2

使用'while'循環來連續檢查值。 –

回答

6

使用do-while循環:

int number; 
do { 
    String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5"); 
    number = Integer.parseInt(textinput); 
} while (!(number >= 0 && number <= 5)); 

編輯:如果你想顯示錯誤信息,請嘗試:

String textinput = JOptionPane.showInputDialog("give me a number between 0 and 5"); 
int number = Integer.parseInt(textinput); 
while (!(number >= 0 && number <= 5)) { 
    textinput = JOptionPane.showInputDialog("error: please a number between 0 and 5"); 
    number = Integer.parseInt(textinput); 
} 
+0

這很快:) –

+1

大聲笑,爲什麼這個答案的票持續上下和上下? :P – Doorknob

+0

有人仍在猶豫,我想:P –

0

編輯:

import javax.swing.*; 
public class Untitled{ 
    public static void main(String[] args){ 
     int in = -1; 
     while(in < 0 || in > 5){ 
      String m = JOptionPane.showInputDialog("enter number"); 
      in = Integer.parseInt(m); 
      if(in < 0 || in > 5){ 
       JOptionPane.showMessageDialog(null,"enter again"); 
      } 
     } 
    } 
} 
+0

你的'while'條件不正確。這將循環直到用戶輸入一個*不正確的*值,此時它將打印「再次輸入」,但退出循環。 –

+0

您的循環對於合法值是無限的。 – Maroun

+0

(此外,這甚至不編譯) – Doorknob

0

如果您的目標是阻止用戶輸入錯誤信息,那麼只需一行代碼即可輕鬆完成。

使用下面

JOptionPane.showInputDialog(parentComponent, message, title, messageType, icon, selectionValues, initialSelectionValue) 

這個格式將給一組預定義值來進行選擇。例如。

JOptionPane.showInputDialog(null, "test", "test", JOptionPane.INFORMATION_MESSAGE, null, new Integer[]{0,1,2,3,4,5}, 0); 

會產生一些輸出這樣

enter image description here

但是如果你需要驗證做到這一點,並引發一些錯誤,你可以按照類似的方法上面。