java - 连续提示输入数字,直到该值落在某个范围内

标签 java

我有一些代码询问即将举行的聚会的客人人数并返回客人人数。我应该对其进行编辑,使其不断提示客人人数,直到该值落在 5 到 100 之间(含)。

这是我目前获取客人数量的方法。

public static int getNumberOfGuests()
{
    Scanner inputDevice = new Scanner(System.in);
    System.out.print("Please enter the number of guests >> ");
    return inputDevice.nextInt();
}

我很新,正在尽力理解。我不确定应该使用什么循环来仍然允许返回客人数量。

最佳答案

正如@user7提到的,您可以使用do-while迭代以做出“直到决定”。

为什么是do-while而不是常规的while?因为它将在检查表达式继续之前执行第一次迭代。

根据您的示例,代码为:

获取客人数量:

import java.util.Scanner;

public class TestGetNumGuest {

    public static void main(String[] args) {
        Scanner inputDevice = new Scanner(System.in);
        getNumberOfGuests(inputDevice);
        System.out.println("ended");
        getNumberOfGuests(inputDevice);
        System.out.println("ended");
        inputDevice.close();
    }
    
    public static int getNumberOfGuests( Scanner inputDevice)
    {
        int numGuests;
        
        do{
            System.out.print("Please enter the number of guests >> ");
            numGuests = inputDevice.nextInt();

        }while(numGuests < 5 || numGuests > 100);
        return numGuests;
    }

}

P.S ScannergetNumberOfGuests() 处理,因为它应该关闭,但如果您在方法内关闭它,您将无法多次调用。

示例 I/O:

Please enter the number of guests >> 1
Please enter the number of guests >> 2
Please enter the number of guests >> 3
Please enter the number of guests >> 4
Please enter the number of guests >> 6
ended
Please enter the number of guests >> 1
Please enter the number of guests >> 2
Please enter the number of guests >> 3
Please enter the number of guests >> 101
Please enter the number of guests >> 100
ended

关于java - 连续提示输入数字,直到该值落在某个范围内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50790309/

相关文章:

java - 如何使用 Spring/MultipartFile 捕获中断的流

java - log4j v1.x 如何向 log4j.xml 添加属性,如 log4j.properties

java - 从 java 中的 hashmap 返回第 n 个值和键

java - 安卓文件扫描

java - 文件打开时出现 Eclipse NullPointerException

java - 如何使用 Mockito 验证带有枚举参数的方法调用?

java - 混淆 Java 中的 long 与 double 行为

java - Webdriver:WAITING PagetoLoad,然后滚动到元素

java - 如何获取用户在 Appolozic 中聊天的联系人列表?

java - 在 Java 中声明方法参数 final 是否有任何性能原因?