billy
billy

Reputation: 1493

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

Okay so I can't seem to find my interest by multiplying inputP * inputR, assuming this is because my scanner variable inputR and inputP are still not converted to double variable even after using this method: System.out.println(inputR.nextDouble()); - What is the problem?

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

    } 
    }
}

Upvotes: 0

Views: 4507

Answers (2)

Tdorno
Tdorno

Reputation: 1571

This snippet won't solve all of your problems but I feel it will set you on the right path.

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

Upvotes: 0

Marko Topolnik
Marko Topolnik

Reputation: 200168

A Scanner variable cannot be "converted to a double". To a Java specialist, even thinking such a thought is alien. You may have a background in dynamic languages such as JavaScript, where this concept would make at least some sense.

What in fact happens is that the nextDouble method returns a double value, and you must capture that value into a double variable, or use it inline.

Another point: you must not use two Scanners on the same input stream. Use just one and call its nextDouble method as many times as you need, it will each time retrieve the next double parsed from the input stream.

Upvotes: 3

Related Questions