user3967885
user3967885

Reputation:

Fahrenheit to Celsius java craches with decimals

I asked this question a while ago and was sent to a question that dont realy answer my question. Problem is that the program works with whole numbers (80f, 40f 60f) etc but crashes once I try decimal numbers (80.5f, 40.5,f 60.5f). I'm new to this, so it may very well be that the answer I was sent to realy does answer my question but I'm not good enough to get it.

import java.util.*;

class temperaturen {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);      

        System.out.println("Enter temperatue in Fahrenheit");
        double number = in.nextInt();
        number = ((number - 32)/1.8);

        System.out.println(number);
    }
}

Upvotes: 0

Views: 159

Answers (4)

user3377697
user3377697

Reputation:

Using in.nextDouble() instead of in.nextInt() you can get rid of the error.

Upvotes: 1

SparkOn
SparkOn

Reputation: 8946

Problem is that the program works with whole numbers

because

nextInt() - Scans the next token of the input as an int. So when you provide a double as input the token does not match the Integer regular expression so it will throw InputMismatchException

So if better use nextDouble() instead

Upvotes: 0

CodeWalker
CodeWalker

Reputation: 2378

Use in.nextDouble() instead of in.nextInt()

To further make your program robust enough to handle errors, you can try Exception Handling Then, your code segment would look like :

try {
     double number = in.nextDouble();
     number = ((number - 32)/1.8);  
        } 
catch (InputMismatchException X) {
     System.out.println("A Numerical Value is expected!");
    }

Upvotes: 2

Dici
Dici

Reputation: 25960

You retrieve a double with nextInt() so no wonder why your program throws an Exception (probably a NumberFormatException). Use nextDouble instead.

Upvotes: 1

Related Questions