繁体   English   中英

如何将我的 while 循环转换为 for 循环?

[英]How do I convert my while loop to a for loop?

我是使用 Netbeans Java 的初学者编码员。 我创建了一个代码,最初询问您的油箱中有多少加仑。 然后,它将有一个 while 循环,询问您第一次运行将行驶多少英里以及您行驶的速度。 这将重复一个 while 循环,直到您输入“0”以停止添加行程。 我很难过如何将此 while 循环转换为仅使用 For 循环。 我将不胜感激。 这是我的具有 while 循环的代码。

public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);
            int tank;
            double miles;
            double speed;
            double totalMiles = 0.0;
            int choice;
            double time;
            double totalTime = 0.0;
            double fuelConsumption;

            System.out.print("How many gallons of gas is in your tank (Integer 1-15)? ");
            tank = input.nextInt();
            System.out.printf("%s%d%s\n\n" , "You have ", tank , " gallons of gas in your tank.");

            System.out.print("Are you going on a trip (1 = Yes or 0 = No)? ");
            choice = input.nextInt();

            while (choice == 1)
            {
                System.out.print("How many miles are you traveling? ");     // miles 
                miles = input.nextFloat();

                System.out.print("What is your speed for this run (MPH)? ");      // speed
                speed = input.nextInt();
                System.out.print("\n");


                totalMiles = totalMiles + miles;
                time = (miles/speed);
                totalTime += (time*60);
                fuelConsumption = (20*(tank/totalMiles));

                System.out.print("Is there another leg in your trip (1 = Yes or 0 = No)? ");    // asking another leg
                choice = input.nextInt();

                if (choice == 0)
                {
                    System.out.printf("%s%5.2f%s\n","Your data for this trip is: \n"
                            + "You traveled a total of about ", totalMiles , " miles.");
                    System.out.printf("%s%.2f%s\n" , "You traveled about " , totalTime , " minutes.");

                    if (fuelConsumption >= 2)
                    {
                        System.out.println("Your car has enough gas to return.");
                        break;

                    }
                    else
                    {
                        System.out.println("Your car will need more gas to return.");
                        break;
                    }


                }
            }

}

}

这不是 for 循环的用例,在这种情况下,我们迭代已知数量的元素以进行已知数量的迭代。 比如,重复 10 次左右。

从技术上讲,它可以用 for 循环解决,但这有点滥用了这个概念。 while 循环非常适合该任务。

这不是使用 for 循环的地方,您可以使用 for 循环来执行以下操作:


printAmount = 10;

for (int i = 0; i < printAmount; i++) {

   System.out.println("Hello World"); 

}

在这里,您将使用 for 循环为 printAmount 中的金额打印“Hi”。

您的情况有所不同:您希望 while 循环在输入为“1”时重复,因此您使用 WHILE 循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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