Scanner assigned by reference

1

I'm trying to collect several numbers to add them. The first number I receive is the number of numbers that will be entered per console, and the rest are the numbers to be added separated by a space, so that the scanner receives something like this:

5 \ n1 2 3 4 5 \ n

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

int i = Integer.parseInt(scanner.nextLine());
int resultado=0;
for (int j=0; j<i; i++){
    resultado += scanner.nextInt();
}
System.out.println(resultado);
}       

It is assumed that in i I keep the first number that I collect, and the rest I add them to result, but my problem is that i is updated every time I do a scanner.nextInt (); and therefore the bluque is not closing.

Is this behavior normal? How can I make the value of i not change, when I continue reading the rest of the numbers? Thanks.

    
asked by pitiklan 21.11.2016 в 19:46
source

1 answer

2

Really in your loop you would have to increase the value of j and not of i .

for (int j=0; j<i; j++){
    resultado += scanner.nextInt();
}

Previously, for each iteration of the loop you were adding 1 more to the value of i . Using j as index the value of i will not vary.

    
answered by 21.11.2016 в 19:50