java小菜鸟一个,在键盘输入时,我只接受整形,但是输入字符时也不能进行报错,只是提醒你输入整形
我暂时一共想到两种方法,一种是:用try catch,另一种是用hasNextInt().
第一种比较麻烦:
public class text1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个整数:");
int a;
boolean b;
do{
b=true;
try {
a=input.nextInt();
} catch (Exception e) {
System.out.println("输入有误,请重新输入!");
input.next();
b=false;
}
}while(b);
}
}
第二种相对代码简单:
public class text1 {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("请输入一个整数:");
while(!input.hasNextInt()){
System.out.println("输入有误请重新输入!");
input.next();
}
int a=input.nextInt();
}
}
希望能与大家交流,不足的地方或还有更优的地方,望各位大神指点