Problem 09 Java

Back to Problem Solutions forum

marcin_l     2015-09-30 20:50:18

Hi, I have a problem with task 9 in Java.

import java.util.Scanner;

public class Solutuion
{
public static void main(String args[])
{
    Scanner input = new Scanner(System.in);
    int counter = input.nextInt();
    int arr[] = new int[3];
    while(counter>0)
    {
        for(int x:arr)
        {
            x = input.nextInt();
            System.out.print(x + " ");
        }

        System.out.print("| ");
        for(int y:arr)
        {
            System.out.print(y + " ");
        }
        System.out.print("||| ");
        counter--;
    }
}
}

This code results in output looking something like this: 449 996 822 | 0 0 0 ||| 1397 855 1885 | 0 0 0 ... My question is why my array gets zeroe'd? What am I doing wrong? Am I stupid?:(

OldProgrammer     2015-09-30 21:16:50

Marcin, in the loop:

    for(int x:arr)
    {
        x = input.nextInt();
        System.out.print(x + " ");
    }

variable x is set to the input value. Nothing is assigned to arr so in the second loop the initial array values of 0 are printed.

Hope that helps.

marcin_l     2015-10-01 15:06:05

Thanks, that helps. I got confused how this enhanced loop works.

Please login and solve 5 problems to be able to post at forum