1

整数を入力すると終了するというステートメントを作成しようとしています。整数で続くものしか作れません。私はまた、特定のエラー魔女をキャッチしようと考えていましたが、NumberFormatExeption私はそれを理解するのに十分ではないことを除いて、これが私のコードです:

import javax.swing.JOptionPane;
import java.lang.NumberFormatException;

public class Calc_Test {
public static void main(String[] args) throws NumberFormatException{
    while(true){
        String INT= JOptionPane.showInputDialog("Enter a number here: ");
        int Int = Integer.parseInt(INT);
        JOptionPane.showConfirmDialog(null, Int);
        break;
        }
    }
}

[編集] 私は自分のコードをいくつかクリーンアップし、スタック オーバーフローに関する友人の助けを借りてこれを思いつきました。コードは次のとおりです。

import javax.swing.JOptionPane;

public class Calc_Test {
public static void main(String[] args){
    while(true){
        String inputInt= JOptionPane.showInputDialog("Enter a number here: ");
        if(inputInt.matches("-?\\d+")){
            JOptionPane.showConfirmDialog(null, "\"" + inputInt + "\"" + " is a number");
            break;
            }
            JOptionPane.showConfirmDialog(null, "\"" + inputInt + "\"" + " is not a number. Therefore, " + "\"" + inputInt + "\"" + " could not be parsed. Try again.");
        }       
    }
}
4

2 に答える 2

2

String#matches()単純な正規表現と一緒に 使用して、入力に数字のみが含まれているかどうかを確認できます。

while(true){
    String input = JOptionPane.showInputDialog("Enter a number here: ");
    if (input.matches("-?\\d+")) {
        int intVal = Integer.parseInt(input);
        JOptionPane.showConfirmDialog(null, intVal);
        break;
    }
}

正規表現-?\\d+、オプションのマイナス記号の後に 1 つ以上の数字が続くことを意味します。正規表現の詳細については、Java チュートリアルの正規表現セクションを参照してください。

Java の命名基準に従って、変数名を小文字で開始するように変更したことに注意してください。

于 2013-05-11T22:57:29.223 に答える
2

ブロックに入れる必要がありtry/catchます。また、変数に適切な名前を付けるようにしてください。これを行う方法の例を次に示します。

while (true) {
    String rawValue = JOptionPane.showInputDialog("Enter a number here: ");
    try {
        int intValue = Integer.parseInt(rawValue);
        JOptionPane.showMessageDialog(null, intValue);
        break;
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "You didn't type a number");
    }
}
于 2013-05-11T22:58:20.340 に答える