java - java while 循环中数字的除数

标签 java while-loop numbers

我有一个为作业编写的 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);
  }
} 

最佳答案

我假设您的其他逻辑很好,那么您可以简单地将 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++;

    }

关于java - java while 循环中数字的除数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26171493/

相关文章:

c - 彼此不匹配的随机数

r - 如何将字符串中的字母转换为R中的数字

algorithm - 如何对任意长度的数字进行平方根和幂运算?

java - 10个问题的力量

java - 检测到 Sqoop 套接字超时 : Read timed out while reading data from Mainframe and insert into Hive

javascript - 关于嵌套while循环矩形的问题

python - 如何在python中停止这个while循环

java - 使用单个 Controller 调用服务依赖于 PathVariable

java - 字符串驻留是否会导致字符串同时位于堆和 native 内存中?

Java Combat Simulator - 我想模拟 1000 场战斗,以跟踪英雄获胜/失败的次数