判断输入的是否为整数,使用递归和循环两种方式实现

1. 使用递归的方式:

public class Test{
    public static int num = 0;

    public static void main(String[] args) {
        System.out.println(Receive(num));
    }
    
    public static int Receive(int mum) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入一个整数");
        try {
            num = sc.nextInt();
        } catch (Exception e) {
            Receive(num);
        }
        return num;
    }
}

如果使用递归的方式:当输入的一直不是数字的情况下,不断递归,不断开辟新的栈,最终会导致爆栈,所以不推荐用这种方式

2. 使用循环的方式


public class Test{
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int num = 0;
        String inputStr = "";
        
        while (true) {

            System.out.println("请输入一个整数:");
            inputStr = scanner.next();
            try {
                num = Integer.parseInt(inputStr); 
                break;
            } catch (NumberFormatException e) {
                System.out.println("你输入的不是一个整数:");
            }
        }

        System.out.println("你输入的值是=" + num);
    }
}

3.需要注意的是:

  1. 这里接收的是字符串类型再转成int类型,如果用nextInt的方式会导致无限循环:
  2. 循环的原因是:
    1)我们创建scanner时,系统会创建内存,我们输入的字母会先存入该内存,当我们使用nextInt()调用时,因为是要调用int类型,所以会抛出异常。
    2)当我们再次要求用户输入时,该内存中的数据并没有被取出,系统会以为内存中的数据是用户输入的,就直接读取内存中的数据,因为还是nextInt()读取数据,读取不出来,所以会一直循环。
    3)代码如下:
class Test{
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = 0;

        while (true) {
            System.out.println("输入整数: ");
            try {
                num = sc.nextInt();
                break;
            } catch (Exception e) {
                System.out.println("输入的不是一个整数");
            }
        }

        System.out.println("输入的数字是:" + num);
    }
}
posted @ 2022-03-24 18:15  她骂我是个大直男  阅读(200)  评论(0)    收藏  举报