java - 如何打印 'while' 的执行次数?

标签 java do-while

我正在编写一个代码,该代码将乘以“x”,直到达到“y”。

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);  
    int x = scan.nextInt();
    int y = scan.nextInt();

    do {
        x = (int)(x*(1.1f));

    }
        while(x < y);

    }

在答案中,我必须获取“while”执行的次数。我不知道该怎么做。

最佳答案

一般的方法是,创建 int 类型的变量 i,并在 while 循环 block 的末尾递增它(这实际上看起来很简单)。总的来说,我会这样做:

public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int x = scan.nextInt();
    int y = scan.nextInt();
    int i = 0;
    do {
        x = (int)(x*(1.1f));
        i++;
    } while (x < y);
    System.out.println("Loop executed " + i + " times.");
}

如果您可以使用 for 循环,请查看以下解决问题的方法:

import java.util.Scanner;

public class Example {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int x = scan.nextInt();
        int y = scan.nextInt();
        int i = 0;
        for (; x < y; i++)
            x = (int)(x*(1.1f));
        System.out.println("Loop executed " + i + " times.");
    }
}

由于 for 循环允许每次迭代执行某些语句,因此您可以在每次循环时增加计数器变量(这可以解决某些使用 continue; 语句的情况)。

关于java - 如何打印 'while' 的执行次数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52686901/

相关文章:

c++ - 为什么 { } while(condition);末尾需要分号但 while(condition) {} 不需要?

java - 用另一个 while 循环 Java 扩展我的程序

c++ - 在 do-while 循环中初始化字符串将在检查条件之前跳转到它

java - 如何持续检查IP是否可达?

java - containsKey HashMap<> 的实现 - Java

java - 为什么 Jtable 中行高自动调整不起作用

java - 使用 Apache Flume 将 MapReduce 作业中的日志写入 HDFS

java - 向现有的 java 程序添加循环?

c# - While 语句 - 键入击键后控制台输出奇怪

java - 可绘制 TextView 的状态列表