0

I'm pretty new to Java arrays and I'm having trouble creating and changing an array as such:

import java.util.Scanner;
public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr = new int[4];
        int num = sc.nextInt();
        if (num % 2 == 0) {
            arr = {2, 4, 6, 8};
        }
        else {
            arr = {1, 3, 5, 7};
        }
        for (int i:arr) {
            System.out.print(i + ", ");
        }
    }

For some reason, it gives me these errors:

test.java:8: error: illegal start of expression
        arr = {2, 4, 6, 8};
              ^
test.java:8: error: not a statement
            arr = {2, 4, 6, 8};
                   ^
test.java:8: error: ';' expected
            arr = {2, 4, 6, 8};
                    ^
test.java:11: error: illegal start of expression
            arr = {1, 3, 5, 7};
                  ^
test.java:11: error: not a statement
            arr = {1, 3, 5, 7};
                   ^
test.java:11: error: ';' expected
            arr = {1, 3, 5, 7};
                    ^
6 errors

I've tried replacing 'int[] arr = new int[4];' with just 'int[] arr;', and to remove the statement and using int[] before 'arr' in the if/else blocks, that doesn't work either. What is causing these errors, and is there a way to work around them?

2 Answers2

2

You can only assigned like that to an array during its initialization, try this instead:

import java.util.Scanner;
public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] arr;
        int num = sc.nextInt();
        if (num % 2 == 0) {
            arr = new int[] {2, 4, 6, 8};
        }
        else {
            arr = new int[] {1, 3, 5, 7};
        }
        for (int i:arr) {
            System.out.print(i + ", ");
        }
    }

Unrelated, but you can simplified your code into :

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();
        int[] arr = (num % 2 == 0) ? new int[]{2, 4, 6, 8} : new int[] {1, 3, 5, 7};
        Arrays.stream(arr).forEach(i -> System.out.print(i + ", "));
    }
}
dreamcrash
  • 36,542
  • 23
  • 64
  • 87
2

Try this:

Scanner sc = new Scanner(System.in);
int[] arr;
int num = sc.nextInt();
if (num % 2 == 0) {
    arr = new int[]{2, 4, 6, 8};
} else {
    arr = new int[]{1, 3, 5, 7};
}
for (int i:arr) {
    System.out.print(i + ", ");
}
Majed Badawi
  • 16,831
  • 3
  • 12
  • 27