-4

targets: scanning numbers (unknown ending), ends when -1 or less is written, prints the smallest number and the first 10 numbers

im trying to get this code work as a school assignment but can't get a code without errors. please help.

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

Ebraheem Alrabeea
  • 2,130
  • 3
  • 23
  • 42

1 Answers1

0

Your issue is Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10 because you use array and fixed the size by 10 and you try to add more than 10 elements int this array, please read this arrayindexoutofboundsexception for more details.

you have to use array list instead of array

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

 arr.add(num); // use this  add new item to array 
Ahmad Al-Kurdi
  • 2,248
  • 3
  • 23
  • 39