What in my code would cause my for loop to terminate prematurely? Am I missing "i" somewhere within the loop?

mightymorphinParkRanger :

I can't figure out what is causing my for loop to terminate. I just tried testing it and it only runs the print function. Then it just terminates. I can't see why it would do this.

import java.util.Scanner;
import java.util.ArrayList;
public class Test092 {

    public static void main(String[] args) {
        Scanner usersVal = new Scanner(System.in);
        ArrayList<Integer> arrayList = new ArrayList<>();

        int valAdd = 0;
        System.out.println("Please provide a list of numbers");

        for (int i = 0; i < arrayList.size(); i++) {

            valAdd = Integer.valueOf(usersVal.nextInt());

            if (valAdd == -1) {
                break;
            }else {
                arrayList.add(valAdd);
            }

        }

    }
}
rhowell :

The issue is that your arrayList doesn't have any elements in it. Therefore, when your loop checks i < arrayList.size() the loop does not run (since arrayList.size() is 0)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=238471&siteId=1