Endless loop while using “try and catch ” block inside a “while loop”

前端 未结 4 949
眼角桃花
眼角桃花 2020-12-21 21:56

My program has an endless loop, when I use try and catch block in a while loop.

import java.util.*;
class Try
{
    public          


        
4条回答
  •  执念已碎
    2020-12-21 22:25

    Scanning an int does not consume the newline charackter (pressing enter). Therefor it reads the newline charackter every time and throws an InputMismatchException.

    You can consume it by simply calling next() or nextLine() after your make your input.

    Note: next() does only work on unix since it reads only one byte and Windows ends a line with two charackters (\r\n).

提交回复
热议问题