我有一些代码要求即将到来的派对的客人数量并返回客人数量。我应该编辑它以使其持续提示客人数量,直到值介于5和100之间。
这是我目前获取客人人数的方法。
public static int getNumberOfGuests()
{
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter the number of guests >> ");
return inputDevice.nextInt();
}
我很新,并尽力去理解。我不确定我应该使用哪个循环仍然允许返回的访客数量。
答案 0 :(得分:0)
作为@ 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;
}
}
PS Scanner
由getNumberOfGuests()
处理,因为它应该关闭,但是如果你在方法中关闭它,你将无法多次调用
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
答案 1 :(得分:0)
一个简单的do-while或while循环将完成这项工作:
class Demo{
public static void main(String[]args){
try(java.util.Scanner sc = new java.util.Scanner(System.in)){
System.out.printf("No. of guest: %d%n", getNumberOfGuests(sc,5,100));
System.out.printf("No. of guest: %d%n", getNumberOfGuests(sc,10,19));
}
}
public static int getNumberOfGuests(final java.util.Scanner sc, final int min, final int max) {
int guest = -1;
do{
System.out.printf("Please enter no. of guest (%d to %d): ", min, max);
if(sc.hasNextInt()){
guest = sc.nextInt();
continue;
}
System.out.println("Kindly input numbers only!");
sc.nextLine();
}while(min > guest || max < guest);
return guest;
}
}