Search code examples
javaarraysassignment-operator

Array Index assignment error with UserInput as If-Else conditional


I am getting an error and I cant quite understand the cause. I'm trying to get user-input using the Scanner method to assign values to the indices of an array, numbers. The user is allowed to keep - continue - entering values into the array numbers, however, if the user decides to stop, entering 0 will break the assignment of array-index values.

    int[] numbers = new int[100];
    int[] countIndex = new int[100];
    int[] numberOcc = new int[100];

    for (int i = 0; i < countIndex.length; i++)
    {
        countIndex[i] = i;
    }

    System.out.println("Enter your integer values: ");
    for (int i = 0; i < numbers.length; i++)
    {

        if(input.nextInt() == 0)
        {
            break;
        }
        else
        {
            numbers[i] = input.nextInt();
        }
    }

This piece of code is a small part of a much larger code, however, it is very important. The error I'm getting is that the code is allowing the user to enter twice before moving to the next index, but the first integer entered it always skipped:

Enter your integer values: 
1
2
0
0 occurs 99 times
2 occurs 1 time

UPDATES

    System.out.println("Enter your integer values: ");
    for (int i = 0; i < numbers.length; i++)
    {
        numbers[i] = input.nextInt();
        if(numbers[i] == 0)
        {
            break;
        }
    }

Why is it that the 1 is ignored as input? Also, is using input.nextInt() as the condition of an if-else statement bad code design?


Solution

  • From the comments

    However, a 0 is still being placed in the index,

    By default, int values will be assigned 0. So when you don't assign non zero values to int, they will still be 0.

    One way around that is to use arraylist. Then once you enter all the numbers, you can convert arraylist to array.

    Simple example without any input validation

    List<Integer> list = new ArrayList<Integer>();
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int[] defaultArray = new int[n];
    // do validation for n
    //assume n = 5 with values 1,2,0,3,2
    for (int i = 0; i < n; i++) {
        int temp = in.nextInt();
    
        if (temp != 0) {
            list.add(temp);
            defaultArray[i] = temp;
        }
    }
    Integer[] positiveArray = new Integer[list.size()];
    positiveArray = list.toArray(positiveArray);
    System.out.println(Arrays.toString(defaultArray));  //will print [1, 2, 0, 3, 2]
    System.out.println(Arrays.toString(positiveArray));  //will print [1, 2, 3, 2]
    

    If you want to convert Integer arraylist to int array, just search on google and there are many similar questions.

    Demo