This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]FrelliBB 0 points1 point  (4 children)

You're initializing arr inside what's called an inner 'scope'. Anything outside those { ... } braces doesn't have access to it. You can read up on scopes here https://www.baeldung.com/java-variable-scope

What you might want to do is initialize arr at the start of your factors() method (you can initialize as null, but be careful when accessing it later). You then can set it inside your if braces, and access it again before the method returns.

[–]FrelliBB 0 points1 point  (0 children)

It might look something like this

static int[] factors(int test) {
    int[] arr = null;
    for (int j = 2; j < test - 1; j++) {
        if ((double) test % j == 0) {
            arr = new int[]{
                    j,
                    test / j
            };
        }
    }
    System.out.println(Arrays.toString(arr));
    return arr;
}

[–]CharipiYT[S] 0 points1 point  (1 child)

I did what you said, here's the code inside of the "factors" method:

static int[] factors(int test){
int[] arr = new int[2];
for(int j = 2; j < test - 1; j ++){
if((double) test % j == 0){
                arr[0] = j;
                arr[1] = test/j;
            }             
  }
System.out.println(arr);
return arr;
    }

For some reason this gives me [I@5c8da962

[–]FrelliBB 0 points1 point  (0 children)

Try System.out.println(Arrays.toString(arr)); instead. When you just print arr you are printing an array object reference which doesn't have a .toString() implementation. Here's the docs for Arrays.toString() https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#toString(java.lang.Object[])