gpt4 book ai didi

java - 如何将这个 while 循环转换为 for 循环?

转载 作者:行者123 更新时间:2023-12-01 18:15:58 25 4
gpt4 key购买 nike

我应该编写将 0 到 10 之间的数字乘以 2 到 10 的代码。它应该使用 for 循环。我能够将其作为 while 循环来想出,但是我尝试转换的任何内容都会给我带来一堆错误。我发布的 while 代码可以工作,它只需要采用 for 循环格式即可。

while(numberCounter <= 10)
{
byTen = numberCounter * 10;
byTwo = numberCounter * 2;
System.out.println(numberCounter + "\t" + byTwo + "\t" + byTen);
numberCounter++;
}

这就是整个问题:

// NewMultiply.java - This program prints the numbers 0 through 10 along
// with these values multiplied by 2 and by 10.
// Input: None.
// Output: Prints the numbers 0 through 10 along with their values multiplied by 2 and by 10.

public class NewMultiply
{
public static void main(String args[])
{

String head1 = "Number: ";
String head2 = "Multiplied by 2: ";
String head3 = "Multiplied by 10: ";
int numberCounter = 0; // Numbers 0 through 10.
int byTen; // Stores the number multiplied by 10.
int byTwo; // Stores the number multiplied by 2.
final int NUM_LOOPS = 10; // Constant used to control loop.

// This is the work done in the housekeeping() method
System.out.println("0 through 10 multiplied by 2 and by 10" + "\n");

// This is the work done in the detailLoop() method
// Write for loop

// This is the work done in the endOfJob() method
System.exit(0);
} // End of main() method.

} // End of NewMultiply class.

我明白了。非常感谢大家的帮助。问题是我有 (numberCounter <= 10) 而不是使用初始化的 NUM_LOOPS。再次感谢!

最佳答案

for语句由初始化变量、结束条件和单步操作三部分组成。您的代码中包含所有这些内容

//initialize
int numberCount = 0;
...
//end condition
while(numberCounter <= 10)
...
//next step
numberCounter++;

您只需将它们放在 for 语句中,然后将 while 循环的剩余逻辑放在 for 语句后面的大括号中

关于java - 如何将这个 while 循环转换为 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60368508/

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