本文介绍了Java:检测变量是String还是Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为我的一些家庭作业寻求帮助。我希望用户输入数字字符串,然后将其转换为整数。但是我想制作一个循环来检测用户是否输入了错误的值,例如One Hundred和100。
I'm look for some help on a bit of homework I have. I want the user to enter a numerical String, then convert it to an Integer. But I want to make a loop that will detect if the user entered in the wrong value such as "One Hundred" as apposed to "100".
我的想法是做这样的事情:
What I was thinking was to do something like this:
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);
但我不知道如何定义整数值。我基本上想要看看它是否是一个数字,以防止它在用户输入错误的东西时崩溃。
But I don't know how to define that "Integer" value. I essentially want it to see if it is a number or not to prevent it from crashing if the user enters the wrong thing.
推荐答案
试试这个
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");
}
}
这篇关于Java:检测变量是String还是Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!