![](/img/trans.png)
[英]How do I return a value from a lambda within the method I want to return on?
[英]How do I return a value from within a for loop?
這是我的代碼:
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;
}
}
我正在嘗試獲取輸出:
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
但是當我運行代碼時,我得到了:
0! = 1
1! = 1
2! = 1
3! = 1
4! = 1
5! = 1
我的問題是,如何通過factorial
靜態方法將for
循環的每次迭代結果返回給main
方法?
您需要刪除return f;
for
循環中的語句。 if
內的返回值將始終在第一次迭代后立即返回到調用方法。 這就是為什么所有階乘的結果都是1的原因。
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
}
正如拉維指出的
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
}
不要在這里返回:
for (int i = 1; i <= n; ++i) {
f *= i;
return f; // here!
}
而是循環結束時 您需要在循環的所有迭代中累積最終結果。
代碼的三個問題:
i = 1
開始 調用factorial(i)
不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 }
返回一次; 循環結束后
for (int i = 1; i <= n; ++i) { f *= i; // return f; // (3) don't return from here } return f;
嗯...您想起了yield
操作(某些語言可用,但Java 不可用 )。 yield
是一個結構,上面寫着:“從函數中返回一個值,但將當前所在的位置添加為書簽,稍后再返回”。 另一方面, return
則表示“返回值並丟棄我所做的一切”。 在Java中,您不能“擱置循環”,以后再返回。
我不理解您要實現的目標不是通過重復計算來浪費時間(僅留下其他答案中提出的收益對性能非常不利 ;僅嘗試更大的數目...)。 您可以通過不產生結果,而是將它們存儲在數組中來實現。 像這樣:
public static void main(String [] args){掃描儀控制台=新的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]);
}
和功能:
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;
}
請注意,以上代碼可能會寫得更好-我試圖盡可能少地修改您的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.