如何使用netbeans 8.1在Java中创建For循环

时间:2017-11-30 23:21:10

标签: java

import java.util.Scanner;

public class ProgAssignment12ForLoop {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
     int time = 0; 
     int speed = 0;
     int distance = 0;

     for (int i = 0, i > 0, i++)
     {
         Scanner keyboard = new Scanner(System.in);
         System.out.println("Please input the speed of the vehicle: ");
         speed = keyboard.nextInt();

         System.out.println("Please input how many hours you've traveled: ");
         time = keyboard.nextInt();

         distance = speed * time;

         System.out.println("the distance you have traveled is " + distance);
         i++;
     } 

     System.out.println("Programmed terminated");

    }

}

这是我想要做的程序类型的提示。 “

使用FOR循环编程此问题 车辆行驶的距离可以如下计算: 距离=速度*时间 例如,如果火车每小时行驶40英里,持续3小时,则行驶的距离为120英里。编写一个程序,询问车辆的速度(以英里/小时计)和行驶的小时数。它应该使用循环来显示车辆为用户指定的每小时一个时间段行进的距离。例如,如果车辆以40英里/小时的速度行驶3小时,则应显示类似于下列报告的报告:

第1小时

距离旅行40

第2小时

距离80

小时3

距离120

1 个答案:

答案 0 :(得分:0)

public static void main(String[] args) {
    int time;
    int speed;

    try (Scanner scan = new Scanner(System.in)) {
        System.out.println("Please input the speed of the vehicle: ");
        speed = scan.nextInt();

        System.out.println("Please input how many hours you've traveled: ");
        time = scan.nextInt();

        for (int i = 1; i <= time; i++) {
            System.out.printf("Hour %d\n", i);
            System.out.printf("Distance Traveled %d\n\n", speed * i);
        }
    }

    System.out.println("Programmed terminated");
}