2013-05-11 183 views
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."); 
     }  
    } 
} 
+0

继续前进,并得到足够好,这并不难。无论如何,你应该可以抓住它。 – ChiefTwoPencils 2013-05-11 23:00:27

+0

@RexPRGMER:负数有效吗?或数字超过22亿? – jlordo 2013-05-11 23:02:33

+0

任何数字都是我们的目标,但我们想出了它 – RexPRGMER 2013-05-11 23:40:40

回答

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教程Regular Expressions section中阅读有关正则表达式的更多信息。

请注意,我已将您的变量名称更改为以小写字母开头,以遵循Java命名标准。

+0

+1。哇。与此相比,我的方法看起来很糟糕。 – Makoto 2013-05-11 22:58:27

+0

“\\ d +”是什么意思? – RexPRGMER 2013-05-11 23:08:42

+0

@RexPRGMER:增加了一个解释和链接进一步阅读。 – Keppil 2013-05-11 23:12:45

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"); 
    } 
} 
+0

我以后自己做了这件事,但是如果它不是int,我希望它重复 – RexPRGMER 2013-05-11 23:10:56