代码如下,我的目的是输入一个int,考虑到用户可能会输入错误,所以我在外面加了try catch,结果如果输入非int就发生了死循环一直输出错误,我想知道:
1.为什么会出现这个问题
2.如何解决类似的输入可能错误的问题?实际工作中也会try catch么package day03;import java.util.Scanner;public class ErrorDemo {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(true){
try {
int a = sc.nextInt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// sc.nextLine();
}
}
}
}
1.为什么会出现这个问题
2.如何解决类似的输入可能错误的问题?实际工作中也会try catch么package day03;import java.util.Scanner;public class ErrorDemo {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(true){
try {
int a = sc.nextInt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// sc.nextLine();
}
}
}
}
Scanner sc = new Scanner(System.in);
while (true) {
try {
int a = sc.nextInt();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
// sc.nextLine();
System.exit(1);
}
}
}
import java.util.*;public class ScannerDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
try{
int i = sc.nextInt();
System.out.println(i);
}catch(InputMismatchException e){
System.out.println("请输入一个数字");
sc.next();
}
}
}
}
被不断的验证,所以不断的报错
import java.util.Scanner;public class ErrorDemo
{
public static void main(String[] args)
{
m();
} public static void m()
{
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
while (sc.hasNext())
{
try
{
int a = sc.nextInt();
System.out.println(a);
}
catch (Exception e)
{ System.out.println("输入不合法");
m();
}
}
}
}