gpt4 book ai didi

java - 无法理解返回类型放置(Big Java Ex 6.8)

转载 作者:行者123 更新时间:2023-12-01 18:03:36 24 4
gpt4 key购买 nike

目前在我书中讨论 for 循环和循环的章节。我有时会遇到一个问题,该方法需要我返回一些东西。例如考虑我的代码以下。基本上,练习是将所有因素按升序排列。现在问题来了

如您所见,我需要在 for 循环之外添加 return 语句。现在我想我的书没有正确解释这一点,或者我不理解这个概念在java中正确返回,但是如果你愿意的话,我们的return语句是否总是必须位于最外层缩进中?

问题是,我真的不想返回 for 循环之外的任何内容。我只想在这种情况下返回 i 。为什么java不让我这样做?什么是好的反击措施?

自从我开始学习循环和for循环以来,我一直很难理解这一点。我想我可以只是 system.out.println(i) 而不是返回它?那么我应该返回什么呢?我猜我还可以将其设置为 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());
}
}

它现在可以工作了(我不太喜欢我的解决方案)

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 可以让您做到这一点。达到条件后返回循环内部没有任何问题。

Java 允许您有多个 return 语句,因此添加另一个 return 0;在允许循环之后。

Java 一旦遇到第一个 return 语句就返回,并且其他 return 语句不会执行(该方法不再执行)(除了一些罕见的边缘情况)使用 try-catch 和 return,但这完全是另一个故事)。

但是为什么需要它?

Java 要求对于所有可能的路径都存在 return使用正确的类型。即使您自己可以从数学上证明 Java 所提示的路径从未被采用,编译器也可能无法证明该路径在运行时是不可能的。因此,您只需在其中添加一个带有虚拟值的返回即可。

在您的具体示例中,存在循环永远不会执行的条件。如果num <= 0 ,则循环条件永远不会满足,并且整个循环体将被跳过。如果没有 return,该方法无效,因为返回类型为 int 的方法不能返回任何内容。 .

因此,在您的示例中,编译器实际上比您更聪明,并且可以防止您犯错误 - 因为它找到了您认为不会发生的路径。

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

从您的评论来看,您似乎想要返回所有因素。在 java 中,函数只能返回一次。这意味着您必须聚合结果并返回 Listarray值:

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
}

关于java - 无法理解返回类型放置(Big Java Ex 6.8),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38664832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com