如何在扫描仪中设置无限循环? [英] How do you set up an infinite loop in scanners?

查看:68
本文介绍了如何在扫描仪中设置无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,所以对此有一个疑问我试图创建一个简单的代码来完成我的工作,只是我想知道您如何设置一个用户可以输入的无限提问的问题?我现在拥有的那个执行无限循环,这无济于事...

I'm a beginner in Java, so I had a question on this I'm trying to create a simple code in which I'm done with it, just I wanted to know how do you set up an infinitely asking question that the user can input? The one I have right now does an infinite loop, which is not helpful...

    import java.util.Scanner;
    public class Logical_Operators {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
    
            Scanner input = new Scanner(System.in);
            
            //this is a conditional scenario, where only boys above the age of 18 can enter
            //and only girls equal to or over the age of 20 
            
            String gender, boy, girl, response;
            int age;
            
            System.out.println("Welcome to the party! Would you like to enter?");
            response = input.nextLine();
        
        while(!response.equals("yes") && !response.equals("no"))    {
            System.out.println("Please say Yes or No");
        }
        {
            
            if(response.equals("yes"))  {       
                
                System.out.println("What gender are you? Type boy or girl.");
                gender = input.nextLine();
                
                System.out.println("What about your age?");
                age = input.nextInt();
                
                    if(gender.equals("boy") && age >= 18)   {
                    System.out.println("You can enter, Welcome!"); 
                    
                }
                    else if(gender.equals("girl") && age >= 20) {
                    System.out.println("You can enter, Welcome!");  }
                 
                    else { System.out.println("Sorry, you may not enter because you don't meet the age requirements");  }
                
            }
            
            else if(!(response.equals("yes")||response.equals("no")))   {
                System.out.println("Please say Yes or No");
                
            }
            
            else { 
                System.out.println("Bye, hope to see you again!");
            }
            
        System.exit(1);
        }
            
        }
    
    }

推荐答案

为了摆脱循环,您需要获取一个新值进行测试

In order to get out of the loop, you need to get a new value to test

response = input.nextLine();

while(!response.equals("yes") && !response.equals("no"))    {
    System.out.println("Please say Yes or No");
    response = input.nextLine();
}

这篇关于如何在扫描仪中设置无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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