简体   繁体   English

了解Java方法

[英]Understanding Java methods

So, I'm very new to Java, I have a summer college course and we're on functions or methods and I'm having a bit of trouble understanding them. 所以,我是Java的新手,我有一个夏季大学课程,我们正在使用函数或方法,我在理解它们时遇到了一些麻烦。

There is a question on a lab I'm having a little trouble with: 在实验室中有一个问题我遇到了一些麻烦:

"Write a method called MaxOfThree that accepts three integer parameters and returns the largest of the three." “编写一个名为MaxOfThree的方法,它接受三个整数参数并返回三个中最大的一个。”

This is what I have so far but I'm not sure whats wrong. 这是我到目前为止,但我不确定什么是错的。 I added the print statement at the end because I wasn't getting a return value when I ran it but now I'm getting errors and it's not compiling. 我在最后添加了print语句,因为我在运行它时没有得到返回值,但是现在我遇到错误并且它没有编译。 If you could help me understand methods a bit more I'd greatly appreciate it. 如果你能帮我理解方法,我会非常感激。 For instance how the parameters work and calling it and if what's included in the function call is correct and how that works. 例如,参数如何工作和调用它以及函数调用中包含的内容是否正确以及它是如何工作的。 I just get so confused when I read through the material and was hoping for an explanation in more layman's terms. 当我阅读材料并希望以更多外行人的术语解释时,我感到很困惑。 Thanks for any help, here is what I have so far. 感谢您的帮助,这是我到目前为止所拥有的。

public class Test {

    public static void main(String[] args) {
        int a = 2, b = 3, c = 4;
        int maxValue = max3(a, b, c);
    }

    public static int max3(int a, int b, int c) {
        int max = a;
        if (b > max) max = b;
        if (c > max) max = c;
        return max;
        System.out.println(max);
    }
}

Here are the errors I'm receiving just in case... 以下是我收到的错误以防万一...

Test.java:16: error: unreachable statement
           System.out.println(max);
           ^
Test.java:17: error: missing return statement
        }
        ^
2 errors

You can't have a statement after the return statement, or to be more exact - a statement imediatelly after a return statement (such as your println) can never be executed, and is therefore an error. 你不能在return语句之后有一个语句,或者更确切地说 - 在一个return语句(例如你的println)之后的一个语句永远不会被执行,因此是一个错误。

The println should be before the return statement. println应该在return语句之前。

    public static int max3(int a, int b, int c) {
       int max = a;
       if (b > max) max = b;
       if (c > max) max = c;
       System.out.println(max);
       return max;
    }

You need to put 你需要把

System.out.println(max);

before: 之前:

return max;

the reason is your return unconditionally ends the function and therefore the compiler won't reach the println causing a compile error. 原因是你的return无条件地结束了函数,因此编译器不会到达println导致编译错误。

The problem is that the compiler detects that execution will never reach the System.out.println line, so it refuses to compile. 问题是编译器检测到执行永远不会到达System.out.println行,所以它拒绝编译。 The line return max; 线路return max; effectively ends the method, so nothing more will run after that. 有效地结束了这个方法,所以在那之后再也没有了。

You should move return max; 你应该移动return max; to below the System.out.println line. System.out.println行下面。

交换最后两行( returnSystem )。

It should be like this, return max statement should be the last line in your method if you want to print something, because return statement goes back or invoke the line that called him,so your print statement is not reach. 它应该是这样的,如果你想打印一些东西, return max语句应该是你方法的最后一行,因为return语句会返回或调用调用它的行,所以你的print语句不能到达。

 public static int max3(int a, int b, int c) {
           int max = a;
           if (b > max) max = b;
           if (c > max) max = c;
           System.out.println(max);
           return max;
        }

You have a System.out.println() statement after the return . return后有一个System.out.println()语句。 return ends the method and so the System.out.println() will never happen because the method will have ended. return结束方法,因此System.out.println()永远不会发生,因为该方法将结束。 That's why you are getting errors. 这就是你得到错误的原因。 Put the System.out.println() before the return : return之前放入System.out.println()

public static int max3(int a, int b, int c) {
       int max = a;
       if (b > max) max = b;
       if (c > max) max = c;
       System.out.println(max);
       return max;
}

I suggest You to change those if statements into one simple for loop with simple int[] vector. 我建议你用简单的int[]向量将那些if语句改成一个简单的for循环。 This solution is much more elegant and flexible. 这种解决方案更加优雅和灵活。 Additionally, You initialized and not used anywhere int maxValue = max3(a, b, c); 另外,你初始化并且没有使用int maxValue = max3(a, b, c); in Your code. 在你的代码中。

public class Demo {
    public static void main(String args[]) {
        int[] numbers = new int[] {2, 3, 4};

        System.out.println(maxValue(numbers));
    }

    public static int maxValue(int[] n) {
        int max = n[0];
        for (int i = 1; i < n.length; i++) {
            if (n[i] > max) {
                max = n[i];
            }
        }
        return max;
    }
}

But let's bow for a moment on the problem of methods implementation in Java. 但是,让我们看一下Java中方法实现的问题。

At the begining of Your journey through the vastness of the Java realm You should get familiar with two types of methods: 1) void methods , and 2) return methods . 在您通过Java领域的广阔之旅的开始之前您应该熟悉两种类型的方法:1) void方法 ,以及2) 返回方法 The first ones are responsible for doing something without returning any value. 第一个负责做某事而不返回任何价值。 We can for example use them for setting values of the fields of our application, initializing GUI, or other operations. 例如,我们可以使用它们来设置应用程序字段的值,初始化GUI或其他操作。 The use of the void method can look like this: void方法的使用可能如下所示:

/* method declaration */
void setValue(int value) {
    someField = value;
}

/* method invocation */
setValue(5);

After invocation of setValue(5) the value of the someField object will be 5 . 调用setValue(5)后, someField对象的值将为5 However, you have to remember about type compatibility, so in this case someField can not be eg of String type. 但是,您必须记住类型兼容性,因此在这种情况下, someField不能是例如String类型。

Second method type mentioned above, ie return method is very useful, when you expect the method to give You an output, eg in result of some operations conducted on the data You've given to Your method. 上面提到的第二种方法类型,即返回方法非常有用,当你希望方法给你一个输出时,例如对你给你的方法的数据进行一些操作的结果。 But of course it's not necessary, to provide for the return method an input. 但是当然没有必要为返回方法提供输入。 Anyway, the use of return method can look like this: 无论如何, 返回方法的使用可能如下所示:

/* method returns text You've given to it */
String getText(String text) {
    return text;
}

/* method returns result of addition of three given int's */
int calculate(int a, int b, int c) {
    return a + b + c;
}

/* method return a random number */
int createRandomNumber() {
    Random random = new Random();
    return random.nextInt();
}

You can easily see, that there is plenty of space for improvisation. 你可以很容易地看到,有足够的空间进行即兴创作。 Basicaly and in summary, void methods can work with given objects, for example can set values and conduct other operations, but thay don't return any STRAIGHT results You can work with. Basicaly和总结, void方法可以使用给定的对象,例如可以设置值并执行其他操作,但是不会返回任何STRAIGHT结果您可以使用。 Return methods , from the other hand, provide You physical results, which You can use in further operations, or even in other methods, for example: 另一方面, 返回方法为您提供物理结果,您可以在进一步的操作中使用它们,甚至可以在其他方法中使用,例如:

import java.util.Random;

public class Demo {

    private static int someValue;

    public static void main(String args[]) {

        setValue(calculate(
        createRandomNumber(), 
        createRandomNumber(), 
        createRandomNumber()));

        System.out.println(someValue);
    }

    public static void setValue(int value) {
        someValue = value;
    }

    public static int calculate(int a, int b, int c) {
        return a + b + c;
    }

    public static int createRandomNumber() {
        Random random = new Random();
        return random.nextInt();
    }
}

The issue with the code you provided is that you're trying to print to the console, after you use your return statement. 您提供的代码的问题是您在使用return语句后尝试打印到控制台。 This causes your program to never reach that line: System.out.println(max); 这会导致程序永远不会到达该行: System.out.println(max);

As already been said, after you return something, the method will end. 如前所述,在您返回某些内容后,该方法将结束。 So your output in the last line of the method will not be executed, so remove it. 因此,不会执行方法最后一行的输出,因此请将其删除。 You can print the returned value of the method when you write the following outside of the method: 在方法外部编写以下内容时,可以打印方法的返回值:

System.out.println("highest value:" + max3(a,b,c));

So now, the 3 values are given to the method which can do something with them now. 所以现在,3个值被赋予了现在可以用它们做某事的方法。 After it did the calculations, the method returns a value, which can now be printed to the console for example. 在完成计算之后,该方法返回一个值,现在可以将其打印到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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