1

I've only just started learning programming in Java and I cannot figure out how to store a value from user input as a double.

Here's my code:

    package FirstProject;
    
       import java.util.Scanner;
    
       public class TripPlanner {
           
           public static void main () {
           Scanner console = new Scanner(System.in);
           System.out.print("How many " + currencySymbol + " are there in 1 USD? ");
           double conversion = console.nextDouble();
           }
       }

I don't understand why when I enter, for example 19.5, it gives me exception error. My understanding is that I defined the conversion variable as double (double conversion) and I expect the user to enter a double (console.nextDouble();). It's fundamental but coming from Python I can't understand what I'm doing wrong.

2
  • Could you please always add what error exactly you are getting? Commented Sep 5, 2020 at 8:14
  • This is the error I get: Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:864) at java.util.Scanner.next(Scanner.java:1485) at java.util.Scanner.nextDouble(Scanner.java:2413) at DoubleProblem.main(DoubleProblem.java:10) Commented Sep 5, 2020 at 10:19

3 Answers 3

2

Using the Scanner like you did is somewhat uncontrolled. For example, the format the scanner expects is locale-dependent. If your system settings are German, for example, then you need to enter 3,7 for a double value of 3.7.

If the format of the entered string is invalid, then an exception will be thrown, probably java.util.InputMismatchException. You should catch the exception and react in a way that's fit to you use case.

To get better control over the locale used, you should instead read a string from the console and then for example use a java.text.NumberFormat. See this question.

Sign up to request clarification or add additional context in comments.

Comments

1

@Leisetreter pointed me in the right direction. It was the keyboard settings. I live in the UK and use the conventions of writing a decimal number with a dot. However, my keyboard was set to Polish programmer's. In Poland decimal numbers are written with a ",". Once I changed the settings I did not have that problem anymore. It would have never occurred to me. Thanks @Leisetreter.

Comments

0

I don't see any mistake in your code. Except from main. The proper way you should call her is public static void main (String args[])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.