让它age的值输入非数字提示输入错误
import javax.swing.*;
public class Test {
public static void main(String[] args){
String name = JOptionPane.showInputDialog("What's your name?");
String input = JOptionPane.showInputDialog("How old are you?");
int age = Integer.parseInt(input);
System.out.println("Hello " + name + ",Next year,you'll be" + (age + 1));
System.exit(0);
}
}int age;
if(age!=?){
age = Integer.parseInt(input);
} else {
System.out.print("输入错误");
}
问号那应该怎么写 不用异常处理的方法
import javax.swing.*;
public class Test {
public static void main(String[] args){
String name = JOptionPane.showInputDialog("What's your name?");
String input = JOptionPane.showInputDialog("How old are you?");
int age = Integer.parseInt(input);
System.out.println("Hello " + name + ",Next year,you'll be" + (age + 1));
System.exit(0);
}
}int age;
if(age!=?){
age = Integer.parseInt(input);
} else {
System.out.print("输入错误");
}
问号那应该怎么写 不用异常处理的方法
int age;
if(Integer.parseInt(input) + 0 != Integer.parseInt(input)){
System.out.print("输入错误");
} else {
age = Integer.parseInt(input);
}
改成下面的试试:
import javax.swing.*;
public class Test {
public static void main(String[] args){
String name = JOptionPane.showInputDialog("What's your name?");
String input = JOptionPane.showInputDialog("How old are you?");
try
{
int age = Integer.parseInt(input);
}
catch(Exception e)
{
System.out.println("输入有误");
}
System.out.println("Hello " + name + ",Next year,you'll be" + (age + 1));
System.exit(0);
}
}
比较简单的做法是
for(char c : input)
if(!Character.isDigit(c))//如果允许小数的话就&&!'.'.equals(c);
//do your things;
并且要大于0 如果是人类的话 还要小于120(应该很高寿了吧)
就按照楼上说的就对了。
if(age instanceof Integer){
age = Integer.parseInt(input);
} else {
System.out.print("输入错误");
}
这样应该可以吧,