2

Here is what I have so far I need to get the miles per hour to be a number with no decimals after it and I am stuck on how to do so. Any help would greatly be appreciated.

P.S. I'm sorry if I posted this wrong its my first time

import java.util.Scanner; 
import static java.lang.System.*;
import static java.lang.Math.*;

public class MilesPerHour
{
    private int distance, hours, minutes;
    private double mph;

    public MilesPerHour()
    {
        setNums(0,0,0);
        mph=0;
    }

    public MilesPerHour(int dist, int hrs, int mins)
    {
        distance = dist;
        hours = hrs;
        minutes = mins;

    }

    public void setNums(int dist, int hrs, int mins)
    {


    }

    public void calcMPH()
    {

        mph = (distance)/(hours + (minutes/60.0));

    }

    public void print()
    {
        System.out.println(distance + " miles in " + hours + " hours and " + minutes + " minutes = " + mph + "MPH.");

    }

    public static void main( String[] args )

    {

    Scanner keyboard = new Scanner(in);

        out.print("Enter the distance :: ");
        int dist = keyboard.nextInt();

        out.print("Enter the hours :: ");
        int hrs = keyboard.nextInt();

        out.print("Enter the minutes :: ");
        int mins = keyboard.nextInt();

        MilesPerHour test = new MilesPerHour(dist, hrs, mins);
        test.calcMPH();
        test.print();
Slava Vedenin
  • 58,326
  • 13
  • 40
  • 59
John Malsov
  • 93
  • 2
  • 8

4 Answers4

1

You can just do:

public void calcMPH()
{

    mph = Math.round((distance)/(hours + (minutes/60.0)));
}
BlackHatSamurai
  • 23,275
  • 22
  • 95
  • 156
1
public void calcMPH()
{

    mph = Math.round((distance)/(hours + (minutes/60.0));

}
Steve Knabe
  • 122
  • 9
1

Java: Use DecimalFormat to format doubles and integers but keep integers without a decimal separator

This should explain how to format numbers exactly as you'd want them. In your case, using setMaximumFractionDigits(0) would be appropriate.

The linked response is of course advanced (but still a good method to know), and there are several easier ways to tackle your specific usecase.

Math.round(your_mph);

and

Math.floor(your_mph);

would both work, as well as typecasting (this is a horrible approach however, and you should avoid doing so.)

mph = (int) mph_calculation;

If you plan on making a larger application with more number-juggling, i'd recommend going for the linked response. If it's just this one usecase, using the quick Math functions are probably a better bet.

Community
  • 1
  • 1
Avenar
  • 341
  • 1
  • 8
0

try this one:

public void calcMPH()
{
    mph = Math.round(distance/1.609);
}
Procrastinator
  • 2,526
  • 30
  • 27
  • 36
  • 2
    This answer would be better if it explained anything about what original code was doing, why that wasn’t correct, and why this is better. – Kaan Jul 04 '22 at 23:19