为什么我的Scanner变量不能转换为double:System.out.println(input.nextDouble());?

时间:2013-10-28 20:30:49

标签: java casting while-loop operators java.util.scanner

好吧所以我似乎无法通过乘以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);

    } 
    }
}

2 个答案:

答案 0 :(得分:3)

Scanner变量不能“转换为double”。对于Java专家来说,甚至认为这样的想法是陌生的。你可能有动态语言的背景知识,比如JavaScript,这个概念至少可以说是有道理的。

实际上发生的是nextDouble方法返回double,您必须将该值捕获到double变量中,或者使用它内联。

另一点:您不得在同一输入流上使用两个Scanners。只使用一个并根据需要多次调用它的nextDouble方法,它将每次检索从输入流解析的下一个double。

答案 1 :(得分: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);