我在试着做一个声明,当你输入一个整数时,它就会终止。我只能做一个以整数继续的数。我也在考虑尝试捕获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.");
}
}
}
发布于 2013-05-11 22:57:29
您可以结合使用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 Tutorials Regular Expressions section中阅读更多关于正则表达式的内容。
请注意,我已经更改了变量名,使其以小写字母开头,以遵循Java命名标准。
发布于 2013-05-11 22:58:20
您需要将其放入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");
}
}
https://stackoverflow.com/questions/16502465
复制相似问题