Domanda

So i have to ask the user whether they are above 18 and they have to answer with a true or false. And keep looping until they enter the right input

So far, i have this

boolean b = false;
do {
    try {
        System.out.print("Are you above 18?");
        Scanner n = new Scanner(System.in);
        boolean bn = s.nextBoolean();

        if (bn == true) {
            // do stuff
        } else if (bn == false) {
            // do stuff
        }

    } catch (InputMismatchException e) {
        System.out.println("Invalid input!");
    }
} while (!b);

HOWEVER, it wont work as the loop keeps going and it wont read the input right and do my if statements. How do i fix this? Thanks!

È stato utile?

Soluzione

slight tweak to your program. This works

boolean b = false;
        do {
            try {
                System.out.print("Are you above 18?");
                Scanner n = new Scanner(System.in);
                boolean bn = n.nextBoolean();
                if (bn == true) {
                    System.out.println("Over 18");
                } else if (bn == false) {
                    System.out.println("under 18");
                }

            } catch (InputMismatchException e) {
                System.out.println("Invalid input!");
            }
        } while (!b);

And the output is

Are you above 18?true
Over 18
Are you above 18?false
under 18
Are you above 18?

Altri suggerimenti

You need to re-check your Scanner statement and Initializing statement...

Scanner n = new Scanner(System.in);
boolean bn = s.nextBoolean();

It should be

Scanner n = new Scanner(System.in);
boolean bn = n.nextBoolean();  

Try changing

boolean bn = s.nextBoolean();

to

b = s.nextBoolean();

Use-

scanner.nextBoolean()

    do{
      try{
          System.out.print("Are you above 18?");
          Scanner scanner = new Scanner(System.in);
          if(scanner.nextBoolean()==true)
           //do stuff

          }else{

          //do stuff
          }
       }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top