when i run a program, and try to type in a decimal as input i always get an error? what can be the problem? should i use int or double? help!

Recommended Answers

All 3 Replies

What you retrieving from user is String. You need to convert this String to double type as follows

double myDouble = Double.parseDouble(myString)

Reference, here

i put the input variable to double though.

heres the code

import java.util.Scanner; 

public class Mileage
    {
    public static void main (String [] args)
    {
        double milesdriven, gallons, milespergallon;    
        // declares milesdriven = amount of miles driven
        //declares gallons = amount of gallons used
        //declares milespergallon = milesdriven divided by gallons  

        System.out.println("This program will calculate mileage"); 
        // Prompts the user the purpose of the program

        System.out.println("Please enter how many miles you have driven:");
        // Prompts the user to enter miles driven

        Scanner keyboard = new Scanner(System.in);


        milesdriven = keyboard.nextInt();
        // Declares milesdriven from what ever the user inputs.

        System.out.println("Please enter how many gallons used:");
        // Prompts the user to enter how many gallons used

        gallons = keyboard.nextInt();
        // Declares gallons from what ever the user inputs.

        milespergallon = milesdriven/gallons;
        // Calculations to find out miles per gallon

        System.out.println("Your car gets " + milespergallon + " miles per gallon.");
        //Displays miles per gallon.

    }
}

milesdriven = keyboard.nextInt();

I'm not exactly sure what Peter Budo is talking about (not that he's wrong, he probably thinks you were talking about a GUI). But the problem here is that you declared your variable as a double (which can hold decimals such as 32.5 etc), but you tried to read in an integer. You code should say

milesdriven = keyboard.nextDouble();

So, to answer your question, int is used to store an Integer value. An Integer being -3, -2, -1, 0, 1, 2, 3 and so on in both directions. Double is used to store decimals such as .12, 34.2, etc. However, in your code, you declared the variable milesdriven as a double, but you tried to read in an Integer. Look at the Javadoc for the nextInt() method.

http://java.sun.com/javase/6/docs/api/java/util/Scanner.html

If you scroll down and find the 'nextInt' method (under Method Summary), look at the return type (where it says int in plain text to the left of nextInt). That indicates that it is returning an int. So when you used the method, you tried to store an int (what it returned) into a double -- hence the error.

Hope that helps. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.