我有一个我为编程编写的Java代码,但是当我们只允许使用while循环时,我使用了for循环。我怎样才能将其转换为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);
}
}
答案 0 :(得分: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++;
}