簡體   English   中英

為什么我的Scanner變量不能通過System.out.println(inputR.nextDouble());轉換為雙精度型?

[英]Why isn't my Scanner variable converting into a double with: System.out.println(inputR.nextDouble());?

好的,所以我似乎無法通過乘以inputP * inputR來發現我的興趣,假設這是因為即使使用此方法后,我的掃描儀變量inputR和inputP仍未轉換為雙變量: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);

    } 
    }
}

Scanner變量不能“轉換為double ”。 對於Java專家來說,甚至認為這樣的想法都是陌生的。 您可能有動態語言(例如JavaScript)的背景知識,這種概念至少在一定程度上是有意義的。

實際上發生的是nextDouble方法返回一個double ,您必須將該值捕獲到double變量中,或內聯使用它。

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

該代碼段無法解決您的所有問題,但我認為它將幫助您走上正確的道路。

    // 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM