简体   繁体   中英

Method that checks if an array value is greater than a user-inputed value

When i try to check if the method i coded is correct or wrong,this error outputs:

"The method existsHigher(int[], int) in the type TBA is not applicable for the arguments (int, int, int)"

I'm having a hard time figuring what is wrong here.


public class test{

public static void main(String[] args) {
    existsHigher([3,2], 5);
    
    
}

public static boolean existsHigher (int[]a, int n) {
    boolean isHigher = false;

    for(int i = 0; i < a.length; i++) {
         int[] b = new int[i];
    
         if(b[i] < n) {
        
        return isHigher;
        }
    }
    return true;
}

}

You should go back and start with basic Java syntax. You'll need to use correct syntax otherwise your programs won't run. It's as simple as that. And there's no guessing, only strict rules. So if you're uncertain google, or read a book.

// instantiate array
var array = new int[]{3, 2};

Also please adhere to Java conventions: Class names should start with an uppercase letter, so Test , not test . Also here: go back to the basics this will be explained in every Java related beginner article.

Another thing: This creates a new array b of length i , but you want to get the i th value of the array a .

int[] b = new int[i];

Therefore use the following:

int b = a[i]

Try to give your variable meaningful names that describe their purpose, a and b are bad variable names.

Your logic also seems to be off given the method name existsHigher() . Here a working example for you to have a comparison:

public class Application {
    public static void main(String[] args) {
        System.out.println(existsHigher(new int[]{3, 2}, 5));
        System.out.println(existsHigher(new int[]{3, 7}, 5));
    }

    public static boolean existsHigher(int[] a, int n) {
        for(int i = 0; i < a.length; i++) {
            int b = a[i];
            if(b > n) return true;
        }
        return false;
    }
}

Expected output:

false
true

Happy Coding:)

Please note: An advanced Java programmer would write this logic probably completely different, but you should not worry about that right now, focus on the basic language constructs and on writing syntactically correct programs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM