Scanner and ArrayList Java

greene029 :

I'm trying to accept user input into this ArrayList with the following code:

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);

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

    for (int i = 0; i < list.size(); i++) {
        System.out.println("Enter numbers, press 0 to exit");
        i = sc.nextInt();
        if (i == 0) {
            break;
        } else {
            list.add(i);
        }
    }
}

The output I'm getting is just [].

Can anybody tell me where I'm going wrong?

Nils :

Your list.size() is 0 at the start, so you won't go into your for-loop. You can do something like

int i = 0;
do {
      System.out.println("Enter numbers, press 0 to exit");
      i = sc.nextInt();
      if(i != 0) {
           list.add(i);
      }
} while(i != 0)

Guess you like

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