break 语句在 java 中不会立即停止执行 while 循环

break statement does not stop executing while loop Immediately in java

提问人:Allen 提问时间:7/23/2023 更新时间:7/27/2023 访问量:55

问:

我正在尝试运行一个程序,要求用户列出一些值。然后,这些值将存储在一个列表中,一旦用户键入 0,循环就应该终止,程序应该找到用户输入的最小和最大值。

我初始化循环以存储值的代码如下:

    public static void main(String[] Args){
        Scanner in = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("This program finds the largest and smallest numbers");
        while(true) {
            System.out.println("?");
            int value = in.nextInt();
            if(value == 0) {break;}
            list.add(value);
        }
        System.out.println("smallest:" + findSmallest(list));
        System.out.println("largest:" + findLargest(list));
    }


break 语句不会在将输入 0 添加到列表之前立即退出 while 循环,而是在整个 while 循环完成后触发。例如,如果我输入 5,3 和 0,我应该得到:

最小:3 最大:5

但相反,我得到:

最小:0 最大:5

为什么会发生这种情况,我该如何解决?

作为参考,以下是整个代码:

package Programs;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FindRange {
    /* sentinel value for exiting the program*/
    private static final int sentinel = 0;
    
    
    public static void main(String[] Args){
        Scanner in = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<>();
        System.out.println("This program finds the largest and smallest numbers");
        while(true) {
            System.out.println("?");
            int value = in.nextInt();
            if(value == 0) {break;}
            list.add(value);
        }
        System.out.println("smallest:" + findSmallest(list));
        System.out.println("largest:" + findLargest(list));
    }
    
    /* 
     * Precondition: We must receive a list of type ArrayList containing
     * int values provided by the user
     * PostConditions: Provides the smallest value in the list 
     * */
    private static int findSmallest(ArrayList<Integer> list){
        int smallest = list.get(0);
        for (int i=0;i<list.size()-1;i++) {
            if (i<smallest) {
                smallest = i;
            }
        }
        return smallest;
                }
    
    /* 
     * Precondition: We must receive a list of type ArrayList containing
     * int values provided by the user
     * PostConditions: Provides the Largest value in the list 
     * 
     * Error with code: Some reason break statement on main doesn't stop the execution of the loop straight away
     * resulting in the sentinel 0 being stored in the list. 
     * */
    private static int findLargest(ArrayList<Integer> list){
        int Largest = list.get(0);
        for (int i=0;i<list.size()-1;i++) {
            if (i>Largest) {
                Largest = i;
            }
        }
        return Largest;
                }
    

}
    
Java while 循环 中断

评论

1赞 Nathan Hughes 7/23/2023
查找方法错误。当你应该把 list.get(i) 放在最小的时候,你把 i 放在了最小的位置。

答:

1赞 Slaw #1

您的工作正常。问题出在 和 的实现中。例如,您有:breakfindSmallestfindLargest

private static int findSmallest(ArrayList<Integer> list){
    int smallest = list.get(0);
    for (int i=0;i<list.size()-1;i++) {
        if (i<smallest) {
            smallest = i;
        }
    }
    return smallest;
}

这里是索引,而不是该索引。此外,您的循环条件是错误的。它已经是排他性的,因为您正在使用 ,这意味着您不应该从列表的大小中减去一个。i<

你想要这样的东西:

private static int findSmallest(ArrayList<Integer> list){
    int smallest = list.get(0);
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) < smallest) {
            smallest = list.get(i);
        }
    }
    return smallest;
}

或者,您可以使用 for-each 循环:

private static int findSmallest(ArrayList<Integer> list){
    int smallest = list.get(0);
    for (Integer value : list) {
        if (value < smallest) {
            smallest = value;
        }
    }
    return smallest;
}

需要对 进行类似的更改。findLargest

1赞 tans flou 7/23/2023 #2

实际上,您不会将列表中的项目与最小变量和最大变量进行比较。您只需将 for 循环的索引与它们进行比较,因此您需要按如下方式更改它们:

private static int findSmallest(ArrayList<Integer> list) {
    int smallest = list.get(0);
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) < smallest) {
            smallest = list.get(i);
        }
    }
    return smallest;
}


private static int findLargest(ArrayList<Integer> list) {
    int Largest = list.get(0);
    for (int i = 0; i < list.size(); i++) {
        if (list.get(i) > Largest) {
            Largest = list.get(i);
        }
    }
    return Largest;
}
0赞 Oleg Cherednik 7/23/2023 #3

实际上,您不需要保留数组。您只需要两个值。int

public static void main(String... args) {
    Scanner scan = new Scanner(System.in);

    System.out.println("This program finds the largest and smallest numbers.");
    System.out.println("Type '0' to exit the program.");

    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;
    boolean empty = true;

    while (true) {
        System.out.print("> ");
        int val = scan.nextInt();

        if (val == 0) {
            break;
        }

        min = Math.min(min, val);
        max = Math.max(max, val);
        empty = false;
    }

    if (empty) {
        System.out.println("No input");
    } else {
        System.out.println("smallest: " + min);
        System.out.println("largest: " + max);
    }
}