Java错误的用户输入循环,直到正确 [英] Java Wrong User Input Loop until correct

查看:178
本文介绍了Java错误的用户输入循环,直到正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您的时间.

我在验证程序时遇到问题.我试过使用While/Switch,但都一样.问题是,当用户输入错误的输入(例如5)时,它会显示错误,然后让他们再次输入错误,但是如果他们再次输入错误的数字,则程序将无法验证...我肯定可以复制代码在其中一次又一次地执行,但是应该有一种更简单的方法.

I have a problem validating the program. I have tried using, While/Switch but it is all the same. The issue is when a user enters the wrong input for example 5, it shows the error and then it lets them type it in again, but if they type in the wrong number again, the program does not validate... I can definitely copy the code again and again within it, but there should be an easier way.

希望您能理解我要达到的目标:D

Hope you understand what I am trying to achieve:D

我怎样才能做到这是一个持续循环?谢谢!

How could I make it so it is a continues loop? Thank you!

//选择合适的房间 public static int rooms(){

// Choosing the right room public static int rooms () {

    int room;

    // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);
    // Displaying a message on the screen
    System.out.println("What room are you in? ");
    // Input
    room = scanner.nextInt();

    if (room==1) {

        roomOne();

    } else if (room==2) {

        roomTwo();

    } else if (room==3) {

        roomThree();

    } else if (room==4) {

        roomFour();

    } else {

        System.out.println("Wrong room number, please enter the room number.");
        room = scanner.nextInt();
    }


    //System.out.println("Sorry but you entered the wrong room number " + room + " Enter the correct room number 1-4 ");    


    return room;

} // End Rooms

推荐答案

您正在寻找一个while循环,类似这样.

You are looking for a while loop, something like this.

我使用do ...来执行该行至少一次.

I use a do ... while to execute the line at least once.

方法检查该值并在不正确的情况下打印一条消息.返回false将阻止代码退出循环并再次读取.

The methods check the value and print a message if this is not correct. Return false will prevent the code to exit the loop and read again.

{
     // Creating a new keyboard input
    Scanner scanner = new Scanner(System.in);


   int room;   
   do {
      // Displaying a message on the screen
      System.out.println("What room are you in? ");
      room = scanner.nextInt();
   } while( !isValid(room) );

   ... //if else or switch
}

private boolean isValid(int room){
   if(room > 4 || room  < 1){
       System.out.println("Try again ;)" );
       return false;
   }  else return true;
}

这是一个快速的代码注释甚至测试.

This is a quick code note even test.

这篇关于Java错误的用户输入循环,直到正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆