【问题标题】:While Loop in Java with ending conditionJava中带有结束条件的while循环
【发布时间】:2017-09-05 15:58:19
【问题描述】:

我正在尝试完成在线 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 循环之外。但是如果没有它在循环内,它不会对更多类型的鸟类重复这个问题。有没有办法让第一个“你看到什么鸟?”在循环中,同时如果满足结束条件,也有一个退出循环的条件?

【问题讨论】:

标签: java while-loop


【解决方案1】:

一种方法(参见代码 cmets):

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
    }
}

【讨论】:

    【解决方案2】:

    试试这个快速解决方案:

    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();
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2015-09-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      相关资源
      最近更新 更多