我有一个while循环,我需要检查while条件中的变量是否为数字。我该怎么做?
do {
try
{
String n = JOptionPane.showInputDialog("Enter a number");
int number= Integer.parseInt(n);
}
catch(NumberFormatException e)
{
System.out.println("Not a Number");
}
} while (????);
System.out.println("You entered a number");
}
}
答案 0 :(得分:1)
您可以使用布尔值:
boolean isNotNumber = true;
do
{
try
{
String n = JOptionPane.showInputDialog("Enter a number");
int number= Integer.parseInt(n);
isNotNumber = false;
}
catch(NumberFormatException e)
{
System.out.println("Not a Number");
}
} while (isNotNumber);
System.out.println("You entered a number");
答案 1 :(得分:0)
您还可以使用以下代码:
do {
try {
String n = JOptionPane.showInputDialog("Enter a number");
int number = Integer.parseInt(n);
if (number <=0|| number >0){
break;
}
} catch (NumberFormatException e) {
System.out.println("Not a Number");
}
} while (true);
System.out.println("You entered a number");
}