【问题标题】:JAVA : How do I input a ( < 0 ) to break the code?JAVA:如何输入 ( < 0 ) 来破解密码?
【发布时间】:2021-01-26 22:51:48
【问题描述】:

2 周后。我需要用一个负整数打破 while 循环,但我一直无法成功实现它。这是我在左右编辑无济于事之前的原始代码。 Print 中的值在循环之外。

public class AssignmentQuestion2 {
    public static void main(String[] args) {
        //write your code here

        ArrayList<Integer> rainfall = new ArrayList<Integer>();
        Scanner in = new Scanner(System.in);

        System.out.println("Please input rainfall(Input negative value to exit)");
        while (in.hasNextInt()) {
            if (in.hasNextInt()) {
                rainfall.add(in.nextInt()); //how to input into array

                System.out.println(calculateAverage(rainfall)); //average
                System.out.println(findSmallest(rainfall)); //smallest input
                System.out.println(findLargest(rainfall)); //largest input
            } else {
                in.close();
            }
        }
    }

【问题讨论】:

    标签: java while-loop break


    【解决方案1】:

    您可以使用(恰当命名的)break 语句来中断循环:

        int r;
        while ((rainfall != null)) {
            if (in.hasNextInt()) {
                r = in.nextInt();
                if (r < 0) {
                     break;
                }
    
                rainfall.add(r); //how to input into array
    
                System.out.println(calculateAverage(rainfall)); //average
                System.out.println(findSmallest(rainfall)); //smallest input
                System.out.println(findLargest(rainfall)); //largest input
            }
        }
    

    【讨论】:

    • 谢谢!我现在还有另一个问题:用于中断的整数被添加到数组中,我需要防止这种情况发生。编辑 - 我通过 T&E 找到了解决方案。再次感谢您!
    猜你喜欢
    • 2014-07-15
    • 2018-12-30
    • 2019-05-25
    • 2016-10-04
    • 1970-01-01
    • 2011-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多