我正在尝试从在线Java教程中完成一项作业,我目前正在讨论有关While循环的问题。这是我的代码:
import java.util.Scanner;
public class bird {
public static void main(String[] args){
Scanner bucky = new Scanner(System.in);
final String end = "END";
String bird;
int amount;
System.out.println("What bird did you see in your garden? ");
bird = bucky.nextLine();
while(!(bird.equals(end))){
System.out.println("How many were in your garden? ");
amount = bucky.nextInt();
}
}
}
我的问题是,如果用户输入END,则代码意味着终止,因此它需要在While循环之外。但如果不在循环内部,它就不会为更多类型的鸟类重复这个问题。有没有办法让第一个"你看到了什么鸟? "如果满足结束条件,循环内部还有条件退出循环?
答案 0 :(得分:0)
一种方法(参见代码注释):
public static void main(String[] args){
Scanner bucky = new Scanner(System.in);
final String end = "END";
String bird;
int amount;
while(true){ // loop "forever"
System.out.println("What bird did you see in your garden? ");
bird = bucky.nextLine();
if (end.equals(bird)) { // break out if END is entered
break;
}
System.out.println("How many were in your garden? ");
amount = bucky.nextInt();
bucky.nextLine(); // consume the newline character after the number
System.out.println("we saw " + amount + " of " + bird); // for debugging
}
}
答案 1 :(得分:0)
试试这个快速解决方案:
import java.util.Scanner;
public class Bird {
public static void main(String[] args){
Scanner bucky = new Scanner(System.in);
System.out.println("What bird did you see in your garden? ");
while(!(bucky.nextLine().equalsIgnoreCase("END"))){
System.out.println("How many were in your garden? ");
bucky.nextInt();
System.out.println("What bird did you see in your garden? ");
bucky.nextLine();
}
}
}