新人在JAVA基础学习中关于nextLine()用法的疑问

import java.util.InputMismatchException;
import java.util.Scanner;
public class Exceptionxuexi {
	
	
	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		Scanner in = new Scanner(System.in);
		boolean continueInput = true;
		
		do {
			try {
				System.out.print("Enter an integer: ");
				int number = in.nextInt();
				
				//Display the result
				System.out.println("The number entered is " + number);
				
				continueInput = false;
			}
			catch(InputMismatchException ex) {
				System.out.println("Try again. (" + "Incorrect input: an integer is required)");
				in.nextLine();
			}
			
		}while(continueInput);
	}

}

 

这是我在学习异常过程中的一个代码段,在catch块中的nextLine方法不太明白是什么用处。

书上写的是,in.nextLine()丢弃当前的输入行,所以用户就可以键入一个新行。

接下来是我认为没有nextLine方法的程序逻辑:

进入循环,我如果输入了一个小数,库函数nextInt()抛出一个异常。

进入catch块,第一行代码输出错误信息。

接着循环继续。进入try块,Enter an integer,接着这里nextInt()还可以让我继续输入啊,可为什么程序运行的时候就是进入死循环,不允许我再次进行输入了呢?请求解答!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值