簡體   English   中英

在Java中,如何檢查輸入是否為數字?

[英]In Java, how do I check if input is a number?

我正在制作一個簡單的程序,可以讓你添加一個比賽的結果,以及他們用完的秒數。 所以為了輸入時間,我這樣做了:

int time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));

所以我的問題是,如果他輸入的數字不是正數,我怎么能向用戶顯示錯誤信息? 就像MessageDialog一樣,在輸入數字之前會給出錯誤。

int time;
try {
    time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
} catch (NumberFormatException e) {
    //error
}

如果Integer.parseInt無法解析int則會拋出NumberFormatException 如果您只想在輸入無效時重試,請將其包裝在while循環中,如下所示:

boolean valid = false;
while (!valid) {
    int time;
    try {
        time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
        if (time >= 0) valid = true;
    } catch (NumberFormatException e) {
        //error
        JOptionPane.showConfirmDialog("Error, not a number. Please try again.");
    }
}

Integer.parseInt當Integer.parseInt的參數不是整數時拋出NumberFormatException,使用try Catch並顯示所需的錯誤消息,將其保存在do while循環中,如下所示

   int   time = -1;
   do{
       try{
            time = Integer.parseInt(JOptionPane.showInputDialog("Enter seconds"));
       }
       catch(NumberFormatException e){

       }
   }while(time<=0);

如果JOptionPane.showInputDialog("Enter seconds")不是有效數字,您將獲得NumberFormatException 。對於正數檢查,只需檢查time >=0

取決於你想如何解決它。 一種簡單的方法是將時間聲明為整數,然后執行:

Integer time;    
while (time == null || time < 0) {
    Ints.tryParse(JOptionPane.showInputDialog("Enter seconds"));
}

當然,這需要你使用谷歌番石榴。 (其中包含許多其他有用的功能)。

另一種方法是使用上面的代碼,但使用標准的tryparse,捕獲NumberFormatException並在catch中不執行任何操作。

有很多方法可以解決這個問題。

或者不重新發明輪子,只需使用:來自Apache Commons Lang NumberUtils.isNumberStringUtils.isNumeric

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM