简体   繁体   English

无法理解返回类型的位置(Big Java Ex 6.8)

[英]Having trouble understanding return type placement( Big Java Ex 6.8)

Currently on the chapter in my book where we talk about for loops and loops. 当前,在我的书的这一章中,我们讨论for循环和循环。 I have sometimes come across an issue where the method needs me to return something. 有时我遇到一个问题,该方法需要我返回一些东西。 For example consider my code below. 例如,考虑下面的代码。 Basically the exercise is to get all the factors in ascending order. 基本上,练习是将所有因素按升序排列。 Now heres the issue 现在这是问题

As you can see I need a return statement outside of the for loop. 如您所见,我需要在for循环之外使用return语句。 Now I guess my book didn't exactly explain this properly, or I didn't understand the concept of return properly in java, but does our return statement always have to be in the most outer indentation if you will? 现在,我想我的书没有完全正确地解释这一点,或者我不理解Java中正确返回的概念,但是如果您愿意,我们的return语句是否总是必须在最外面的缩进中?

The thing is, I don't really want to return anything outside of the for loop. 问题是,我真的不想在for循环之外返回任何东西。 I just want to return i upon that condition. 我只想在那种情况下还i Why doesn't java let me do this? 为什么Java不让我这样做? Whats a good counter-action? 有什么好的反作用?

Ever since I started learning loops and for loops, I have been having trouble understanding this. 自从我开始学习循环和for循环以来,我一直很难理解这一点。 I guess I could just system.out.println(i) instead of returning it? 我想我可以只使用system.out.println(i)而不返回它? But then what should I return ? 但后来我应该怎么return I could also make it a void type, and then make another method to print it, I guess? 我还可以将其设置为void类型,然后再创建另一种方法来打印它,我猜吗?

class factors{

    private int num;

    public factors(int num)
    {
        this.num = num;
    }

    public int getFactors()
    {
        for(int i = 1 ; i<num ; i++)
        {
            if (num % i == 0)
            {
                return i;
            }
        }
         // I NEED TO PUT A RETURN STATEMENT HERE

    }   
}

public class test{
    public static void main(String [] args)
    {
        factors fact = new factors(20);
        System.out.println(fact.getFactors());
    }
}

IT WORKS NOW ( I dont particularly like my solution) 现在就可以工作(我不太喜欢我的解决方案)

class factors{

    private int num;

    public factors(int num)
    {
        this.num = num;
    }

    public void getFactors()
    {
        for(int i = 1 ; i<num ; i++)
        {
            if (num % i == 0)
            {
                System.out.println(i);
            }

        }   
    }





}

public class test{
    public static void main(String [] args)
    {
        factors fact = new factors(20);
        fact.getFactors();
    }
}

The thing is, I don't really want to return anything outside of the for loop. 问题是,我真的不想在for循环之外返回任何东西。 I just want to return i upon that condition. 我只想在那种情况下还我。 Why doesn't java let me do this? 为什么Java不让我这样做?

Java lets you do that. Java使您可以做到这一点。 There is nothing wrong with returning inside the loop upon reaching the condition. 达到条件后,在循环内部返回是没有问题的。

Java allows you to have multiple return statements, so adding another return 0; Java允许您有多个return语句,因此添加另一个return 0; after the loop is allowed. 允许循环之后。

Java returns once it hits the first return statement, and other return statements are not executed (the method isn't executed anymore) (except for some rare edge cases with try-catch and return, but thats another story entirely). Java到达第一个 return语句后即返回,并且其他return语句执行(该方法不再执行)(除了一些罕见的带有try-catch和return的极端情况,但这完全是另一回事)。

But why is it required? 但是为什么要这样做呢?

Java requires that for all possible paths there exists a return with the proper type. Java要求,对于所有可能的路径 ,必须存在具有正确类型的return Even if you yourself can proof mathematically that the path Java complains about is never taken, the compiler might not be able to prove that the path is not possible at runtime . 即使您自己可以数学证明Java抱怨的路径都不会被采用,编译器也可能无法在运行时证明该路径是不可能 So you simply need to add an return there with a dummy value. 因此,您只需要在其中添加带有虚拟值的返回值即可。

In your concrete example , there is a condition in which the loop gets never executed. 在您的具体示例中 ,存在循环永远不会执行的情况。 If num <= 0 , then the loop condition is never satified and the entire loop body is skipped. 如果num <= 0 ,则永远不会满足循环条件,并且跳过整个循环主体。 Without the return,the method is invalid, because you can't return nothing from an method with return type int . 如果没有返回值,则该方法无效,因为您无法从具有返回类型int的方法中返回任何内容。

So, in your example, the compiler is actually smarter then you, and prevents you from making a mistake - because it found the path you thought wouldn't occur. 因此,在您的示例中,编译器实际上比您聪明,并且可以防止您犯错误-因为它找到了您认为不会发生的路径。

new factors(-1).getFactors(); // you don't check the passed value at all ;)

From your comments, it seems that you want to return all factors. 从您的评论看来,您想返回所有因素。 In java, you return once, and only once, from a function. 在Java中,从函数返回一次,并且仅返回一次。 This means you have to aggregate the results and return a List or array of values: 这意味着您必须汇总结果并返回一个List或值array

public List<Integer> getFactors(int num) {
    List<Integer> factors = new ArrayList<>();
    for (int i = 1 ; i<num ; i++)
    {
        if (num % i == 0)
        {
            factors.add(i);
        }
    }
    return factors;
}

public static void main(String[] args) {
    System.out.println(Arrays.toString(new factors(20).getFactors());
    // prints a comma-separated list of all factors
}

does our return statement always have to be in the most outer indentation if you will? 如果您愿意,我们的return语句是否总是必须位于最外面的缩进位置?

No. 没有。

However , all potential code paths must return something. 但是所有潜在的代码路径都必须返回某些内容。 Consider this structure: 考虑以下结构:

for(int i = 1 ; i<num ; i++)
{
    if (num % i == 0)
    {
        return i;
    }
}

What happens if num is a value where the loop itself is never entered? 如果num是一个永不输入循环本身的值,会发生什么情况? Or what happens if the if condition is never satisfied? 或者, if从不满足if条件,会发生什么? No return statement would ever be encountered, which is invalid. 不会遇到任何return语句,这是无效的。

The compiler has to guarantee that the method will return something , under any and all potential runtime conditions. 编译器必须保证该方法将在任何和所有潜在的运行时条件下返回某些内容 So while it's perfectly valid to return from within the loop, you also must provide logic for what to return if that return statement is never reached. 因此,虽然从循环内返回是完全有效的,但如果从未到达该return语句,则还必须提供返回逻辑。

Java doesn't let you do that because what happens if the if (num % i == 0) is never true? Java不允许您这样做,因为如果if (num % i == 0)永远不为真会发生什么?

The methods return type is int , so it has to return an int . 方法的返回类型为int ,因此它必须返回一个int And it's possible that the if statement could be false, not every condition is covered with a return statement. 而且if语句可能为假,并非每个条件都由return语句覆盖。

So if you wanted to you could return something like -1, or another invalid value. 因此,如果您愿意,可以返回-1或其他无效值。 Then you know that the function didn't find what it was looking for. 然后,您知道该函数没有找到它想要的东西。

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

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