簡體   English   中英

如何將此while循環轉換為for循環?

[英]How do I convert this while loop into a for loop?

我應該編寫將 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 語句之后的大括號中

我想出了這個,它執行我想要的,但是,它說我沒有使用 for 循環?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM