简体   繁体   中英

divisors of a number java while loop

I have this Java code that I wrote for an assignment, however I used a for loop, when we were only allowed to use while loops. How would I be able to convert this to a while loop?

The intention of the code is to take the input numbers that are separated by commas, and tell how many consecutive duplicate numbers there are. ie 1,1 is consecutive, but 2,1,2 is not.

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);
  }
} 

I assume your other logic is good then you can simply convert the for into while loop as mentioned here:

    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++;

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM