Java 如何使用扫描仪获取布尔用户输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23667462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:35:36  来源:igfitidea点击:

How to get boolean user input using scanner?

javainputboolean

提问by tash517

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

所以我必须问用户他们是否超过 18 岁,他们必须回答真假。并继续循环直到他们输入正确的输入

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!

但是,它不会在循环继续进行时起作用,并且不会正确读取输入并执行我的 if 语句。我该如何解决?谢谢!

采纳答案by vkg

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?

回答by Code-Apprentice

Try changing

尝试改变

boolean bn = s.nextBoolean();

to

b = s.nextBoolean();

回答by Hello World

Use-

用-

scanner.nextBoolean()

扫描仪.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
          }
       }

回答by Rajat.r2

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

您需要重新检查您的 Scanner 语句和 Initializing 语句...

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

It should be

它应该是

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