Click here to Skip to main content
15,498,943 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This code is for comparing two numeric arrays but has a few errors.
Please help?
Errors:
1.Cannot make a static reference to the non-static method func(int[], int[], int) from the type 
2.This method must return a result of type boolean


What I have tried:

package packageMe2;

import java.util.Scanner;

public class Tamrin2 {

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

		int size;
		System.out.print("Please Enter array1 size : ");
		size = reader.nextInt();

		int[] arr = new int[size];
		System.out.println("Enter array1 elements : ");
		for (int i = 0; i < size; i++) {
			arr[i] = reader.nextInt();
		}
		int size2;
		System.out.print("Please Enter array2 size : ");
		size2 = reader.nextInt();

		int[] arr2 = new int[size2];
		System.out.println("Enter array2 elements : ");
		for (int j = 0; j < size2; j++) {
			arr2[j] = reader.nextInt();
		}
		boolean flag;
		if (size != size2) {
			System.out.println("Are not equal");
		} else {
			flag = func(arr, arr2, size);
			System.out.println(flag); } 
	}
	boolean func(int arr[], int arr2[], int size) {
		int sizeArr = size;
		for (int k = 0; k < sizeArr; k++) {
			if (arr[k] == arr2[k]) {
				return true;
			} else {
				return false;
			}
		}

	}
}
Posted
Updated 28-Aug-21 3:42am

1 solution

You cannot call an instance function without an instance reference. In this case just make it static. You also need to return a value at the end of the function. It would also be better to test every element of the arrays:
Java
static boolean func(int arr[], int arr2[], int size) {
    boolean array_equal = true; // assume the arrays are equal
    int sizeArr = size;
    for (int k = 0; k < sizeArr; k++) {
        if (arr[k] != arr2[k]) {
            array_equal = false; // found unequal valuse, so set the flag
            break;               // and break out of the loop
        }
    }
    return array_equal;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900