I need to type number 2 times after my scanner scan the input

Tomek Młynarski :

Could you help me to understand why I need to type 2 times to allow scanner to scan my input data. What I am basically check in below piece of code is to validate if number is a int type and is above 0 to ask number of players playing the game (guessing number game)

Validation code works perfectly fine but...I need to type digit 2 times...

package pakiet;

import java.util.Random;
import java.util.Scanner;

public class GraModyfikacjaLiczbyGraczy {

    public static void main(String[] args) {

        Random rand = new Random();
        int los = rand.nextInt(11);
        int liczbaGraczy;  // number of players

        Scanner scan7 = new Scanner(System.in); // zamknac
        System.out.println("Type number of players");

        while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
            System.out.println("Type number of players");
            scan7 = new Scanner(System.in);

        }
        liczbaGraczy = scan7.nextInt();
Dipankar Baghel :

You initialize Scanner 2 times thats why -

In while loop -

while (!scan7.hasNextInt() || scan7.nextInt() < 0) {
    System.out.println("Type number of players");
    //Issue here
    scan7 = new Scanner(System.in);
}

You can simply use scan7.next() for next input.

You can use do-While loop properly to achieve this -

public static void main(String[] args) {

        Random rand = new Random();
        int los = rand.nextInt(11);
        int liczbaGraczy;  // number of players

        Scanner scan7 = new Scanner(System.in); // zamknac
        System.out.println("Type number of players");

        do {
            while (!scan7.hasNextInt()){
                System.out.println(" Type number of players :");
                scan7.next();
            }
            liczbaGraczy = scan7.nextInt();
        }while (liczbaGraczy < 0);


        System.out.println("Number of players :"+liczbaGraczy);
}

Hope this will help.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=421279&siteId=1