简体   繁体   中英

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

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM