我正在尝试声明,当您输入整数时终止。我只能用整数继续。我也正在考虑尝试捕获特定错误,但女巫是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.");
        }
    }
}

最佳答案

您需要将其放入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");
    }
}

关于java - while语句出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16502465/

10-10 13:08