2014-10-03 51 views
1

我有這個Java代碼,我寫了一個任務,但是我使用for循環,當我們只允許使用while循環。我將如何能夠將其轉換爲while循環?數字java除法器while循環

該代碼的意圖是採用以逗號分隔的輸入數字,並告知有多少個連續的重複數字。即1,1是連續的,但是2,1,2不是。

import java.util.Scanner; 

public class ConsecDouplicates { 

    public static void main(String[] args) { 

Scanner scan = new Scanner(System.in); 


System.out.print("Enter numbers: "); 
String str = scan.nextLine(); 


String[] numbers = str.split(","); 

Integer last = null; 
Integer current = null; 
int total = 0; 

for (String number: numbers) { 

    current = Integer.parseInt(number); 


    if (last != null) { 
    if(last == current){ 
     System.out.println("Duplicates: " + current); 
     total = total +1; 
    } 
    } 
    last = current; 

} 
System.out.println("Total duplicates: " + total); 
    } 
} 

回答

2

我假設你的其他邏輯是好的,那麼你可以將for簡單地轉換成while循環這裏提到:

int count = 0; 

    while (count < numbers.length) { 

     current = Integer.parseInt(numbers[count]); 


     if (last != null) { 
     if(last == current){ 
      System.out.println("Duplicates: " + current); 
      total = total +1; 
     } 
     } 
     last = current; 
     count++; 

    } 
+0

感謝,完美的工作,我有很多的問題,當談到僅使用while循環的邏輯。 – cooldudsk 2014-10-03 01:46:39