2013-02-19 115 views
2

我正在寻找一些有关我的功课的帮助。我希望用户输入一个数字字符串,然后将其转换为整数。但是我想制作一个循环来检测用户是否输入了错误的值,例如“One Hundred”与“100”相对应。Java:检测变量是一个字符串还是一个整数

我在想什么是应该做这样的事情:

do{ 
     numStr = JOptionPane.showInputDialog("Please enter a year in numarical form:" 
         + "\n(Ex. 1995):"); 
     num = Integer.parseInt(numStr); 
      if(num!=Integer){ 
      tryagainstr=JOptionPane.showInputDialog("Entered value is not acceptable." 
            + "\nPress 1 to try again or Press 2 to exit."); 
    tryagain=Integer.parseInt(tryagainstr); 
      } 
      else{ 
      *Rest of the code...* 
      } 
      }while (tryagain==1); 

但我不知道如何定义“整数”的价值。我基本上想让它看看它是否是一个数字,或者如果用户输入错误的东西来防止它崩溃。

+1

'尝试'的东西。 – 2013-02-19 16:05:20

+2

['Integer.parseInt'](http://docs.oracle.com/javase/6/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29)方法抛出'NumberFormatException'如果输入不能作为整数解析。你只需要使用'try/catch'。 – 2013-02-19 16:07:21

回答

1

试试这个

int num; 
String s = JOptionPane.showInputDialog("Enter a number please"); 
while(true) 
{ 
    if(s==null) 
     break; // if you press cancel it will exit 
    try { 
     num=Integer.parseInt(s); 
     break; 
    } catch(NumberFormatException ex) 
    { 
     s = JOptionPane.showInputDialog("Not a number , Try Again"); 
    } 
} 
+0

谢谢!我现在更好地理解try/catch。我运行了类似于这个的地方,我告诉它在变量等于1时执行{try/catch},并且每次进入catch时变量都保持1以保持循环。谢谢! – Dave555 2013-02-20 15:29:03

5

试试这个:

try{ 
     Integer.valueOf(str); 
    } catch (NumberFormatException e) { 
     //not an integer 
    } 
1

使用正则表达式验证字符串的格式,并在其上只接受数值:

Pattern.matches("/^\d+$/", numStr) 

matches方法将返回true如果numString包含有效的数字序列,但当然输入可以高于Integer的容量。在这种情况下,您可以考虑切换到longBigInteger类型。

1

尝试使用instanceof,如果你想整间只检查这种方法将帮助您检查多种类型

之间例

if (s instanceof String){ 
// s is String 
}else if(s instanceof Integer){ 
// s is Integer value 
} 

和字符串,你可以使用@NKukhar代码

try{ 
     Integer.valueOf(str); 
    } catch (NumberFormatException e) { 
     //not an integer 
    } 
相关问题