简体   繁体   中英

How do I return a value from within a for loop?

Here's my code:

import java.util.*;

public class factorialdisplay {
  // Main Method. Prints out results of methods below.
  public static void main(String[] args) {
    Scanner console = new Scanner(System.in);

    // Asks user for input
    System.out.println("Please enter a number: ");
    int n = console.nextInt();

    for (int i = 0; i <= n; ++i) {
      System.out.println(i + "! = " + factorial(n));
    }
  }

  public static int factorial (int n) {
    int f = 1;
    for (int i = 1; i <= n; ++i) {
      f *= i;
      return f;
    }
  return f;
  }
}

I'm trying to get the output:

1! = 1 
2! = 2 
3! = 6 
4! = 24 
5! = 120

But when I run the code, I get this:

0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1

My question is, how would I return the result of each iteration of a for loop, through the factorial static method, to the main method?

You need to remove the return f; statement which is there in the for loop. The return within the if will always return to the calling method immediately after the first iteration. And that is why you're getting 1 as the result for all the factorials.

public static int factorial (int n) {
    int f = 1;
    for (int i = 1; i <= n; ++i) {
      f *= i;
      // return f; // Not needed - this is causing the problem
    }
    return f; // This is your required return
}

And as Ravi pointed out

for (int i = 1; i <= n; ++i) { // well 0 will return 1 as well, so no prob unless you don't need 0 factorial
  System.out.println(i + "! = " + factorial(i)); // you need to pass i instead of n as i is the counter here
}

Don't return here:

for (int i = 1; i <= n; ++i) {
  f *= i;
  return f; // here!
}

but rather at the end of your loop. You need to accumulate your final result over all iterations of your loop.

Three problems with the code:

  1. Start at i = 1
  2. Call factorial(i) not factorial(n)

     for (int i = 1; i <= n; ++i) { // (1) start at i = 1 System.out.println(i + "! = " + factorial(i)); // (2) pass i not n } 
  3. Return once; after the loop ends

     for (int i = 1; i <= n; ++i) { f *= i; // return f; // (3) don't return from here } return f; 

Hmmm... you sort of think of a yield operation (which is available in some languages, but not Java). yield is a construct which says: "return a value from the function, but bookmark the place where I currently am and let me come back to it later". return on the other hand says something like "return the value and discard everything I do". In Java, you can't "put a loop on hold" and come back to it later.

I undestand that what you are trying to achieve is not wasting time by repeating calculations (and just leaving the return which has been proposed in other answers is incredibly bad for performance ; justr try it for some bigger numbers...). You could achieve it by not yielding the results, but storing them in an array. Like this:

public static void main(String[] args) { Scanner console = new Scanner(System.in);

// Asks user for input
System.out.println("Please enter a number: ");
int n = console.nextInt();

int[] results = factorials(n);
for (int i = 0; i <= n; ++i) {
  System.out.println(i + "! = " + results[i]);
}

and the function:

public static int[] factorials (int n) {
  int[] results = new int[n + 1];
  results[0] = 1;

  int f = 1;
  for (int i = 1; i <= n; ++i) {
    f *= i;
    results[i] = f;
  }
 return results;

}

Note that the above could be written better - I tried to modify your code as little as possible.

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