2015-12-09 69 views
1

我該如何格式化它,以便在計算每小時英里數後顯示無小數點?我不知道如何格式化這一切。我目前得到的是它是四捨五入的,但它後面留下.0,它看起來不正確。我也必須保留它作爲double切斷小數點

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 = Math.round((distance)/(hours + (minutes/60))); 
    } 

    public void print() { 
    System.out.print(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(); 
    } 
} 
+0

它轉換爲int。 – DBug

+0

double會在轉換爲字符串時顯示.0。所以,你可以把它轉換爲int System.out.print(距離+「英里in」+ hours +「hours and」+ minutes +「minutes =」+((int)mph)+「MPH。」);' – user3162662

回答

2

你可以使用String.format()來顯示你的雙圓爲整數:

System.out.println("My number: " + String.format("%.0f", 2.5d)); 

將顯示My number: 3

有關String格式化程序的語法,請參閱full documentation

+1

你可以使用它,或者如果你願意,你可以使用[DecimalFormat](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) – liquidsystem

+0

也許他使用'Math .round()'作爲值,而不僅僅是顯示它。 –

1

從代碼:

private double mph; 

mph仍將double即使你分配Math.round()的返回值吧。並且當您調用System.out.print()時,mph被引用爲double,導致尾隨「.0」。

只需添加投這樣會做一個類型:

System.out.print(" MPH: " + ((int)mph));