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+表示可选的减号,后跟一个或多个数字。您可以在 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 回答