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?