2013-10-28 43 views
0

好吧,我似乎無法通過乘以inputP * inputR來找到我的興趣,假設這是因爲即使在使用此方法後,我的scanner變量inputR和inputP仍未轉換爲雙變量:System.out.println(inputR。 nextDouble()); - 問題是什麼?爲什麼我的Scanner變量不能轉換爲雙精度型:System.out.println(inputR.nextDouble());?

import java.util.Scanner; 

public class test { 


    //This program will display the value of the principle for each of the next 5 years 

    public static void main(String[] args) { 

Scanner inputR = new Scanner(System.in); Scanner inputP = new Scanner(System.in); 
double years = 0; 

    System.out.println("Please enter the principle value for year one: "); 

    System.out.println(inputP.nextDouble()); 


    System.out.println("Please enter the interest rate for year one: "); 

    System.out.println(inputR.nextDouble()); 

    while (years < 5) { 

    double interest; 
    years = years + 1; 

     interest = inputP * inputR; 

     principle = inputP + interest; 

     System.out.println("Your principle after 5 years is: " + principle); 

    } 
    } 
} 
+2

您正試圖乘以2臺掃描儀。這是不會做得很好的..嘗試將你從掃描儀獲得的輸入存儲在雙變量中,並使這些變量多樣化。 –

回答

3

Scanner變量不能是 「轉換爲double」。對於Java專家來說,即使認爲這樣的想法是陌生的。您可能擁有動態語言(如JavaScript)的背景,在這種背景下,這個概念至少有一定意義。

什麼實際上發生的是nextDouble方法返回double,你必須捕捉價值爲double變量,或在線使用。

另一點:你不能在同一個輸入流上使用兩個Scanners。只需使用一次並根據需要調用其nextDouble方法多次,它將每次檢索從輸入流中解析出的下一個double。

0

這段代碼並不能解決你所有的問題,但我覺得它會讓你走上正確的道路。

// This program will display the value of the principle for each of the 
    // next 5 years 

    Scanner input = new Scanner(System.in); 
    Double principle, interest; 
    int year = 0; 

    //System.out.println("Please enter the year value: "); 
    //year = input.nextInt(); 

    System.out.println("Please enter the principle value: "); 
    principle = input.nextDouble(); 

    System.out.println("Please enter the interest rate: "); 
    interest = input.nextDouble(); 

    while (year < 5) { 
     interest = interest + interest; 
     principle = principle + interest; 
     year++; 
    } 

    System.out.println("Your principle after 5 years is: " + principle);