Error handling reading ints from Scanner in while loop

user3077627

I am try to catch an exception and get it to repeat, but it just creates an endless loop and then crashes the program... why is it doing this? Is it something wrong with my catch?

I have looked around the web and stackoverflow and can only find answers that don't related to what I am trying to achieve.

        boolean bError = true;
        System.out.println("How many players");
        do
        {
            try
            {
                PLAYERS = input.nextInt();

                if(PLAYERS > 5)
                {
                    System.out.println("maximum of 5");
                }//if
                else
                {
                    bError = false;
                }

            }
            catch(InputMismatchException e)
            {
                System.out.println(e);
                bError = true;
            }

        }while(bError && PLAYERS > 5);
Jason C

It goes into an endless loop if you enter an invalid number because the invalid token is still left on the stream, and nextInt() keeps trying over and over again to grab it.

You will have to get the data off the stream.

One thing you could do is use nextLine() instead, then explicitly try and parse the returned String into an integer (e.g. with Integer.parseInt()).

Another thing you could do is call input.next() (or input.nextLine()) in the exception handler, to read (and discard) the garbage input. You may have to tweak the Scanner delimiters to get next() to work for you if it's not meeting your requirements with default settings.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Infinity loop while reading data from file

분류에서Dev

do while loop with input scanner

분류에서Dev

Scanner not stopping from reading input

분류에서Dev

How to not read the header row while reading csv using Scanner?

분류에서Dev

I/O error while communicating with scanner

분류에서Dev

While/for loop error

분류에서Dev

Error in while loop?

분류에서Dev

reading input from user in a loop

분류에서Dev

Error while reading csv file in R

분류에서Dev

Error while reading csv file in R

분류에서Dev

Detect empty lines while reading from file

분류에서Dev

Wrong file path while reading from UI

분류에서Dev

Breaking from nested while loop

분류에서Dev

Incorrect output from while loop

분류에서Dev

Bash: reading input within while read loop doesn't work

분류에서Dev

unexpected behavior of while loop variable with scanf reading string

분류에서Dev

Querying with a string converted from an array of ints, results in Conversion data type smallint error

분류에서Dev

Addition Operation from ints in a String

분류에서Dev

Continue while from nested for-loop

분류에서Dev

Reading text file in java using scanner

분류에서Dev

Backbone.js - each method throw error, while loop the models

분류에서Dev

PHP-EWS while loop error Cannot redeclare class EwsSendEmail

분류에서Dev

Error while importing "from visual import *"

분류에서Dev

utilizing for loop while downloading data from server using function in R?

분류에서Dev

Count the total number of names in a 'while loop' from user input, in Python

분류에서Dev

How handling relationships in CoreData while retrieving data from JSON + Swift Or ObjC

분류에서Dev

Receiving an error while passing an argument from a view to a method from controller

분류에서Dev

Global error handling in ExtJS

분류에서Dev

Error Handling mechanism

Related 관련 기사

뜨겁다태그

보관