2011-06-26 59 views
1

我是java新手,想知道如何將用戶輸入(整數)更改爲十進制形式。例如,如果用戶輸入年度利息6,則在計算完成並打印答案之前將其更改爲0.06。如何將用戶輸入從整數更改爲十進制

此程序僅用於確定銀行帳戶將持續多長時間..但我也應該以年和月格式打印此。我不知道如何做到這一點,除了放入另一個if語句並說if(從上面的計算得到的結果大於12)從計算中減去12並將add1減去一年..並以某種方式將其放入循環中。

如果任何人有建議/指示給予這樣做真的會有所幫助!

import java.util.*; 

class Two { 
    public static void main(String[] args) { 
    Scanner imp = new Scanner(System.in); 
    System.out.print("Enter your initial balance: "); 
    double bal = imp.nextDouble(); 
    System.out.print("Enter your yearly interest: "); 
    double intr = imp.nextInt(); 
    System.out.print("Enter your monthly withdrawls: "); 
    double wtd = imp.nextDouble(); 
    if (true) { //need to change 
     System.out.print("Your account will last " + (((bal*intr) + bal)/ wtd) + " months"); 
    } else { System.out.print("The account will last forever"); 

    } 
    } 

}

回答

3

你可以乘以0.01(雖然從int到double的轉換需要以某種方式發生,但這避免了明確的轉換)

double intr = imp.nextInt()*0.01; 

和轉移月進入年+月檢查出整數除法和模運算

int months = 18;//calculated 

int years = month/12;//integer division is a implicitly rounded down 
months = months%12; 

,或者如果你真的需要做一個循環

int months = 18;//calculated 
int years = 0; 
while(months >= 12){ 
    months -= 12; 
    years += 1; 
} 
+0

+1,避免了顯式的轉換 - 整齊。 – mre

3

你要轉換爲百分比,所以你必須通過100這裏來劃分是一個可能的解決方案:

double intrAsDouble = ((double)intr)/100; 

哦,至於日期的事情:

int totalMonths = ((bal*intrAsDouble) + bal))/wtd; 
int years = (int)(totalMonths/12); 
int months = totalMonths%12; 

String accountWillLast = ""; 

boolean hasMonths = months != 0; 
boolean hasYears = years != 0; 

if (hasYears) { 
    accountWillLast = accountWillLast + years; 
    if (years == 1) accountWillLast = accountWillLast + " year"; 
    else accountWillLast = accountWillLast + " years"; 
} 
if (hasMonths && hasYears) { 
    accountWillLast = accountWillLast + " and "; 
} 
if (hasMonths) { 
    accountWillLast = accountWillLast + months; 
    if (months == 1) accountWillLast = accountWillLast + " month"; 
    else accountWillLast = accountWillLast + " months"; 
} 
相關問題