【问题标题】:How do I convert this while loop into a for loop?如何将此 while 循环转换为 for 循环?
【发布时间】:2020-02-24 01:30:43
【问题描述】:

我应该编写将 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

【问题讨论】:

标签: java for-loop while-loop


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:

    我想出了这个,它执行我想要的,但是,它说我没有使用 for 循环?

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

    【讨论】:

    • 这应该是对您的问题的修改而不是答案。是什么告诉您您没有使用 for 循环?
    • 对不起。我仍在学习如何工作。为我提供反馈的程序。它表明我得到了正确的答案。但它说我没有使用 for 循环
    • 尝试在循环本身中初始化变量,类似于for(int numberCounter = 1; numberCounter &lt;= 10; numberCounter++)
    • 它没有改变任何东西。我认为我需要以某种方式包含的唯一内容是 NUM_LOOPS,但我不知道在哪里或如何
    • 你可以在 for 语句中说 numberCounter
    猜你喜欢
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-01
    • 1970-01-01
    • 2023-01-22
    • 2018-03-19
    • 2017-02-14
    相关资源
    最近更新 更多