我有一些代码询问即将举行的聚会的客人人数并返回客人人数。我应该对其进行编辑,使其不断提示客人人数,直到该值落在 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 Scanner
由 getNumberOfGuests()
处理,因为它应该关闭,但如果您在方法内关闭它,您将无法多次调用。
示例 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/