PankajKushwaha
PankajKushwaha

Reputation: 928

ArrayList with Scanner not Working Properly

This code is supposed to store Integers in the ArrayList and exit when the number 42 is entered, but it is not working. Sometimes the loop does not stop when 42 is supplied and sometimes it does not store all the numbers entered prior to 42.

import java.util.*;
class test{    
    public static void main(String[] args){    
        ArrayList<Integer> ar = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);
        while(sc.nextInt() != 42){
            ar.add(sc.nextInt());
        }    
        for(int i : ar){
            System.out.println(i);    
        }    
    }
}

Output:

C:\Users\pj\Desktop\j2\new>java test
1
2
3
5
42
2
5

Upvotes: 1

Views: 194

Answers (2)

Kalakuh
Kalakuh

Reputation: 41

These three lines cause the problem; you are asking user input twice

while(sc.nextInt() != 42){
    ar.add(sc.nextInt());
}

You should store the value to a variable, like this

int n = sc.nextInt();
while (n != 42) {
    ar.add(n);
    n = sc.nextInt();
}

Hopefully that helps :)

Upvotes: 0

Eran
Eran

Reputation: 393781

while(sc.nextInt() != 42){
    ar.add(sc.nextInt());
}

You are reading two ints in each iteration, so it's possible you are reading the 42 inside the loop, and therefore you don't stop when you read it.

Try to change it to :

int i = 0;
while((i = sc.nextInt()) != 42){
    ar.add(i);
}

Upvotes: 4

Related Questions