Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

file - My objects in my array are going to null (java)

I have this while loop that is pulling information from a file and making new objects and then placing the objects into an array and for some reason the while loop iterates once for each if statement and then exits so all the other lines are made null. Here is my while loop

// open file and create array
        File file = new File("Adventures.txt");
        Scanner myReader = new Scanner(file);
        Adventure[] array = new Adventure[myReader.nextInt()];
        int i = 0;
        // reading file
        while (myReader.hasNext()) {
            if ("Zipline".equals(myReader.next())) {
                array[i] = new Zipline(myReader.nextDouble(), myReader.nextDouble());
                i++;
            }
            if ("Snorkel".equals(myReader.next())) {
                array[i] = new Snorkel(myReader.nextDouble(), myReader.nextDouble());
                i++;
            }
            if ("Helicopter".equals(myReader.next())) {
                array[i] = new Helicopter(myReader.nextDouble(), myReader.nextDouble());
                i++;
            }
        } // while loop
    ```
question from:https://stackoverflow.com/questions/66059348/my-objects-in-my-array-are-going-to-null-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Each iteration of the loop is using too many values, because each call to myReader.next() is consuming another token. Store the token in a variable, so you can check it multiple times.

while (myReader.hasNext()) {
    String token = myReader.next();
    if ("Zipline".equals(token)) {
        array[i++] = new Zipline(myReader.nextDouble(), myReader.nextDouble());
    }
    if ("Snorkel".equals(token)) {
        array[i++] = new Snorkel(myReader.nextDouble(), myReader.nextDouble());
    }
    if ("Helicopter".equals(token)) {
        array[i++] = new Helicopter(myReader.nextDouble(), myReader.nextDouble());
    }
} // while loop

Or use a switch statement:

while (myReader.hasNext()) {
    switch (myReader.next()) {
        case "Zipline":
            array[i++] = new Zipline(myReader.nextDouble(), myReader.nextDouble());
            break;
        case "Snorkel":
            array[i++] = new Snorkel(myReader.nextDouble(), myReader.nextDouble());
            break;
        case "Helicopter":
            array[i++] = new Helicopter(myReader.nextDouble(), myReader.nextDouble());
            break;
    }
} // while loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...