开发者

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 para开发者_C百科meter 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.


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}));
}


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);
    }
}


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜