简体   繁体   中英

Distance Traveled loop help Java

I've been racking my brain trying to figure out why my program isn't looping right. Rather than getting each hour increments I'm only getting the final hour/speed. So if I put that I'm going 40 mph for 3 hours I only get 120.

Here is the problem:

The distance a vehicle travels can be calculated as follows: Distance = Speed * Time For example, if a train travels 40 miles-per-hour for three hours, the distance traveled is 120 miles. Write a program that asks for the speed of a vehicle (in mph) and the number of hours it has traveled. It should use a loop to display the distance a vehicle has traveled for each hour of a time period specified by the user. For example, if a vehicle is traveling at 40 mph for a three-hour time period, it should display a report similar to the one that follows: Hour Distance Traveled

1 40

2 80

3 120

import java.util.Scanner;

public class Distance{
  public static void main(String [] args){
  Scanner keyboard = new Scanner(System.in);

  int time , speed ,  hour;
  double  distance;

  System.out.println("How fast were you going ?");
  speed = keyboard.nextInt();

  while(speed<=0)
  {
     System.out.println("Please enter a valid speed ");
     speed = keyboard.nextInt();
  }

  System.out.println(" How long did you ride / drive ?");
  time = keyboard.nextInt();

  while(time<=0)
  {
     System.out.println("Please enter a valid time ");
     time = keyboard.nextInt();
  }

  System.out.println(" Hour                         Distance");
  System.out.println("---------------------------------");
  hour = 0;


  for( int x = 1; x<=time; x++)
  {
     hour++;
     if(hour>1)
     {
        distance = time * speed;
        System.out.println(time+ "                " +distance);
     }
    }
   }
  }

use hour inside your loop instead of time,

 for( int x = 1; x<=time; x++) {
     hour++;
     if(hour>1) {
         distance = hour * speed;
         System.out.println(hour+ "                " +distance);
     }
 }

or just use x

Delete the variables hour and distance .

Change the name of the loop variable from x to hour .

Simply your loop to:

for( int hour = 1; hour <= time; hour++)
    System.out.println(hour+ " " + (hour * speed));

Note that if you did used your distance variable, it was a double which is the wrong type, because:

  • both speed and time are int , so distance must be int
  • the output of a double has a decimal point, but your requirements did not show one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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