简体   繁体   中英

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. 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. 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?

The thing is, I don't really want to return anything outside of the for loop. I just want to return i upon that condition. Why doesn't java let me do this? Whats a good counter-action?

Ever since I started learning loops and for loops, I have been having trouble understanding this. I guess I could just system.out.println(i) instead of returning it? But then what should I return ? I could also make it a void type, and then make another method to print it, I guess?

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. I just want to return i upon that condition. Why doesn't java let me do this?

Java lets you do that. 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; 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).

But why is it required?

Java requires that for all possible paths there exists a return with the proper type. 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 . 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. Without the return,the method is invalid, because you can't return nothing from an method with return type 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. This means you have to aggregate the results and return a List or array of values:

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?

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? Or what happens if the if condition is never satisfied? No return statement would ever be encountered, which is invalid.

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.

Java doesn't let you do that because what happens if the if (num % i == 0) is never true?

The methods return type is int , so it has to return an int . And it's possible that the if statement could be false, not every condition is covered with a return statement.

So if you wanted to you could return something like -1, or another invalid value. Then you know that the function didn't find what it was looking for.

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