0

What I want to do: read strings from keyboard using Scanner until specific string is used to break the infinite loop. save them in an arrayList, then pass them into an array with its length beeing the number of the iteration of the loop

public class InputReader {
    ArrayList<Integer> list = new ArrayList<>(0);
    int arrayLength;
    String readInput;
    Scanner ir = new Scanner(System.in);
    void readInput() {

        for (int m=0; ;m++) {
                readInput = ir.nextLine();
                if ("q".equals(readInput)) {
                    //problem: arrayLength does not have the value of m outside the loop
                    arrayLength = m;
                    break;
                }         
                System.out.println("arrayLength: "+arrayLength);
                intInput = Integer.parseInt(readInput);
                list.add(intInput);
            }    
        }
        int[] array = new int[arrayLength];
    }
}

Inside the loop arrayLength works perfectly but outside the loop it has no value as I initialized it without value. Because of this,

System.out.println("array.length: "+array.length);

always returns 0 and the compiler returns this error:

java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

when I try to save integers inside the array. 1) How can I make the changes to the variable stay outside the loop?

2) Weird observation A:

int[] array = new int[list.size()];

returns the same error despite list.size() having the right value even outside the loop (checked by printing it).

And B: The code works if I create my array inside another method instead of inside the class and then use it in the method, but this way I cannot use it in my other classes despite using inheritance or parameters.

void giveOutput() {
    int[] array = new int[list.size()];
    public void giveOutput () {
        System.out.println("list.size()"+list.size());
        System.out.println("array.length:"+array.length);
        for (int n=0; n<list.size(); n++) {
            array[n] = list.get(n);
            System.out.print("array["+n+"]:"+array[n]+" ");
        }
    }
}

this creates a working array but I cant hand it over to my Minsort extends InputReader subclass where it is sorted which leads to question number

3) How to use variables initialized in methods in other classes? This way my program could work too.

(I am a bloody beginner, started seriously working with java yesterday, my first succesful project was a Minsort-Algorithm I wrote from scratch so please have mercy. And thanks in advance.)

  • your intention is a bit confusing in the code (look at the braces carefully), so yes, the line ` int[] array = new int[arrayLength];` is outside of the method `readInput`, thus, it's an instance variable created and initialized once the object is created. – UninformedUser Dec 09 '18 at 04:25

1 Answers1

1

The array array is initialized when an object of the type InputReader is instantiated, not after the readInput() method is run.

In other words, array is always initialized when you use new InputReader(), not after the readInput() method is run. That means that the arrayLength variable has not yet been modified at the moment when array is created, so the default value for an int is used, which is 0.

Try this:

public static class InputReader {
        ArrayList<Integer> list = new ArrayList<>(0);
        int arrayLength;
        String readInput;
        Scanner ir = new Scanner(System.in);
        int[] array;
        void readInput() {

            for (int m=0; ;m++) {
                readInput = ir.nextLine();
                if ("q".equals(readInput)) {
                    //problem: arrayLength does not have the value of m outside the loop
                    arrayLength = m;
                    break;
                }

                int intInput = Integer.parseInt(readInput);
                list.add(intInput);
            }
            System.out.println("arrayLength: "+arrayLength);
            array = new int[arrayLength];
        }
    }

Also, your System.out.println("arrayLength: "+arrayLength); always returned 0 because the arrayLength changes only when q is pressed.

To answer your third point: You could create a getter function in the class InputReader. For example:

    public int[] getArray() {
        return array;
    }

As a side-note: It is very good practice to have your instance variables be declared with a private access modifier, and to then create public getter and setters. This is called Encapsulation, and is an OOP principle (my advice is that you google the OOP principles).
More info about getters and accessors here: Why use getters and setters/accessors?

Victor10
  • 96
  • 7
  • "The array array is initialized when an object of the type InputReader is instantiated, not after the readInput() method is run." Didnt know that. Very helpful. My code is working now. Thanks for the fast and friendly answer ;) – CaptainChrom Dec 08 '18 at 20:21