nextInt() 接收异常bug

4 篇文章 0 订阅

nextInt() 接收异常bug

废话不多说先看代码

package com.Class;

import java.util.Scanner;

/**
@author HelloWorld
@create 2021-04-22-13:56
@email 154803771@qq.com
*/public class Test0 {
    public static void main(String[] args) {
        int num;
        Scanner scanner = new Scanner(System.in);
        while (true) {
            try{
                System.out.print("Input num: ");
                num = scanner.nextInt();
                break;
            } catch (Exception e) {
                System.out.println("Error! Input again!");
            }
        }
    }
}

在这里插入图片描述

说明

一段很简单的代码,只接受键盘录入的 int 类型数据,但是当第一次输入不为 int 类型时,程序会死循环。。。

分析

nextint() 会接收 Error! Input again!,所以就会一直报异常,并且不能再次输入

解决办法

  1. 重新定义输入流,关闭上次的输入流
public static void main(String[] args) {
    int num;
    while (true) {
        try{
            Scanner scanner = new Scanner(System.in);
            System.out.print("Input num: ");
            num = scanner.nextInt();
            break;
        } catch (Exception e) {
            System.out.println("Error! Input again!");
        }
    }
}

在这里插入图片描述

  1. 用next() 接收Error! Input again!
public static void main(String[] args) {
    int num;
    Scanner scanner = new Scanner(System.in);
    while (true) {
        try{
            System.out.print("Input num: ");
            num = scanner.nextInt();
            break;
        } catch (Exception e) {
            System.out.println("Error! Input again!");
            scanner.next();
        }
    }
}

Peace and love, no war and no bug!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值