2016-06-13 97 views
-8

對不起,我被困在轉換這做while while循環可以請任何人幫助我。java如何轉換爲循環做while循環

int sum = 0; 
int num; 

System.out.print("Enter number: "); 
num = sc.nextInt(); 
// Store the user input into variable num        

// Complete the for loop to start from 1 
// and end at num 

for (int i = 1 ; i <=num ; i++) 
    sum += i; 

System.out.println("The sum is " + sum); 

,這是我的do while循環

int sum = 0; 
int num; 

int i = 1; 

do { 
    sum += i; 
    System.out.print("Enter number: "); 
    num = sc.nextInt(); 
    i++; 
} while (i <= num); 

System.out.println("The sum is " + sum); 
+0

你的while循環執行num + 1次。 – Maroun

+0

當你的輸入*在for循環和*在while循環中時,你可能會有不同的行爲。 – Filburt

+1

'for'循環首先檢查條件以查看它是否可以迭代,'do-while'首先迭代,然後檢查條件是否應該再次迭代。如果你想要有完全相同的行爲,你需要在輸入'do-while'之前添加條件檢查,但是在這一點上它意味着你應該簡單地使用'while {}'循環。 – Pshemo

回答

3
int sum = 0; 
    int num; 
    int i = 0; 
    System.out.print("Enter number: "); 
    num = sc.nextInt(); 
    do{ 
    sum += i; 
    i++; 
    } 
    while (i <=num); 

    System.out.println("The sum is " + sum); 

初始化我到零,因爲DO-而第一做檢查,而不是爲第一檢查前做了。而且你的do-while將和你的for一樣。或者你的do-while將會有1的總和,即使你的num是0.相對於你而言,如果num爲0,sum = 0。

+0

爲什麼把System.out.print(「Enter number:」);和num = sc.nextInt();循環 – stevenTan

+1

的另一面,因爲只需要一次該變量,除非將其添加到總和中 – alan

+0

@stevenTan提示:您還在原始代碼中的'for'循環之外使用該變量。這是爲什麼? – Pshemo

1

在第一種情況下,您在for之外輸入num值,您在do/while上執行第二種情況。所以,我認爲要做到這一點:

//Variables 
int sum = 0; 
int num; 
int i = 0; 

//Select num 
System.out.print("Enter number: "); 
num = sc.nextInt(); 

do { 
    sum += i; 
    i++; 
} while (i <=num); 

System.out.println("The sum is " + sum); 
0

首先,你可能需要研究循環多一點的基礎知識。 while循環和do-while循環之間的區別是條件被檢查的地方。執行代碼塊後,Do-while循環檢查條件。 while循環沒有。它在執行前檢查。

int num = sc.nextInt(); 
int i = 1; 
int sum = 0; 
do{ 
    sum += i; 
     i++; 
}while(i <= num);  //check condition after the running do block 
System.out.println(sum); 

**這取決於您的輸入。這意味着如果您的輸入爲零,答案將是錯誤的。因爲你的i = 1和總和等於1.