简体   繁体   中英

Question about Static methods

The question asks for the user to enter. lets forget about that and make it already initialized with some values so I can understand the first part.

Write a static method public static int findMax(int[] r) which receives as a parameter an array of numbers of type int and returns the maximum value. Write a main method to test your program with array size 10 and elements entered by user.

Can't get what you exactly want to do? But if want that one class has static method and other class in main access that then you can try like this..

public class Demo {
    public static void main(String[] args) {
        int i = FindMaxClass.findMax(new int[10]); // pass int array
        System.out.print(i);
    }
}

class FindMaxClass{
    public static int findMax(int[] r){
        //logic to find max.
        return 0; // return the max value found.
    }
}

If static method should be in same class then others answers are good/correct.

I'm not going to write the code to solve your exact problem, but I'll tell you how to create and call a static method. See the example below:

public class Test {

    // This is a static method
    static void myMethod(int myArg) {
        System.out.println("Inside Test.myMethod " + myArg);
    }

    // This is how to call it from main()
    public static void main(String[] args) {
        myMethod(3);
    }
}
public static int findMax(int[] values) {
    int max = Integer.MIN_VALUE;
    for (int val : values) {
        if (val > max) {
            max = val;
        }
    }
    return max;
}

public static void main(String[] args) {
    System.out.println("Max value: " + findMax(new int[]{1,2,3,1,2,3}));
}

If you need more information to static methods take a look at:

http://openbook.galileocomputing.de/javainsel/javainsel_05_003.htm#mjd51d5220468ee4a1f2a07b6796bb393b

But you already know how to iterate over arrays?

Or maybe you are able to be more specific what you do not understand and what you have tried yet?

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