我希望我的程序只有当actor变量为< = 5&&时才会执行某些代码。大于0 否则我想回去再次提出不同的问题:
System.out.println("\nEnter actors number(max.5): ");
int actorsNumber = scanner.nextInt();
scanner.nextLine();
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
所以当条件为假时,例如演员数= 7,那么我想告诉用户:&#34;输入有效的演员号码(1-5)&#34;如果actorsnumber是1-5而不是再次询问,那么再次执行for循环&#34;输入有效的演员编号(1-5)&#34;
答案 0 :(得分:0)
while(!scanner.nextLine().equals("quit")) {
if (actorsNumber <= 5 && actorsnumber>0) {
for (int i = 1; i <= actorsNumber; i++) {
System.out.println("\nEnter name and surname of the " + i + " actor: ");
String[] parts2 = scanner.nextLine().split("\\s+");
String actName = parts2[0];
String actSurname = parts2[1];
actorName.add(actName);
actorSurname.add(actSurname);
}
}
}
或类似的东西,重点是,在扫描仪上使用while循环。
答案 1 :(得分:0)
正如@apexlol所说,你的代码应该是一个循环。但是,do-while
循环比while
循环更方便,因为这样循环无论如何都至少执行一次。
答案 2 :(得分:0)
您需要让用户在循环中输入数字。循环的条件将是你的if的条件。然后在退出循环后(这意味着用户输入正确的数字),输入你的for循环。
这将是这样的:
int actorsNumber = -1; //force a wrong value at the beginning
while(actorsNumber < 1 || actorsNumber > 5) {
//Ask user to enter a number between 1 and 5
//store this number in actorsNumber
}
//As we exited the while-loop, actorsNumber is between 1 and 5
//Put your for-loop here