我有一些代码要求下一次聚会的来宾人数并返回来宾人数。我应该对其进行编辑,以使其连续提示客人人数,直到该值落在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
?因为它将在检查表达式继续之前执行第一次迭代。
根据您的示例,代码将是:
getNumberOfGuests:
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/