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.

Tom
  • 33
  • 9
  • Could you please always add what error exactly you are getting? – Jakob F Sep 05 '20 at 08: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) – Tom Sep 05 '20 at 10:19

3 Answers3

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.

Leisetreter
  • 133
  • 1
  • 9
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.

Tom
  • 33
  • 9
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[])