运行JAVA代码时出错

时间:2018-01-21 12:44:27

标签: java

  

目标:   扫描数字(未知结束),写入-1或更少时结束,打印最小数字和前10个数字

我试图让这段代码作为学校作业,但无法获得没有错误的代码。请帮忙。

public class Sheela1 {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean isPrice = true;
        int i = 0;
        int[] arr = new int[10];
        int min = 0;

        while (isPrice = true) {
            System.out.println("enter num");
            int num = scan.nextInt();
            if ((num > -1) && (i <= 10)) {
                isPrice = true;
                arr[i] = num;
            } else if ((num > -1) && (i > 10)) {
                isPrice = true;
            } else if (num <= -1) {
                isPrice = false;
            }

            if ((i == 0) && (min == 0)) {
                min = num;
            } else if ((i > 0) && (num < min)) {
                min = num;
            }
            if (i < 10) {
                System.out.println("num " + (i + 1) + " " + "in the first 10: " + arr[i]);
            } else {
                System.out.println(num);
            }
            i = i + 1;
        }
        System.out.println("min: " + min);
    }
}

the code in eclipse

1 个答案:

答案 0 :(得分:0)

您的问题是Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10,因为您使用数组并将大小固定为10,并尝试在此数组中添加10个以上的元素, 有关详细信息,请阅读此arrayindexoutofboundsexception

你必须使用数组列表而不是数组

 ArrayList<Integer> arr = new ArrayList<Integer>();

 arr.add(num); // use this  add new item to array