Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

JavaWorld Daily Brew

Please please help me!

Tags:

Hi, i'm really really new to Java and programming in general. I'm working my way through the Java for Dummies book and came across a problem with one of the examples. Here is the code:

import java.util.Scanner;

class VersatileSnitSoft {

   public static void main(String args[]) {
   Scanner myScanner = new Scanner(System.in);
   double amount;

   System.out.print("What's the price of a CD-ROM? ");
   amount = myScanner.nextDouble();
   amount = amount + 25.00;

   System.out.print("We will bill $");
   System.out.print(amount);
   System.out.println(" to your credit card.");
   }
}

Now, the program compiles but it crashes if i enter in a value with a decimal point.

Here's the output after i enter a value with a decimal point.

What's the price of a CD-ROM? 5.75
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextDouble(Scanner.java:2387)
at VersatileSnitSoft.main(VersatileSnitSoft.java:10)

Process completed.

Any help would be greatly appriciated. Thanks.

Your rating: None

Use comma instead of dot and

Use comma instead of dot and enjoy!

Or try this code if You want

Or try this code if You want to use dot

< amount = myScanner.nextDouble();
> amount = Double.parseDouble(myScanner.next());

Based on your results can

Based on your results can one assume you're using a PC with locale settings such that decimal points are represented by a character other than ".", then?

The Scanner class by default will use the locale settings for the current runtime environment, so without overriding them, if you're someplace where "one thousand one hundred and fifty and 53 hundredths" is written "1.150,53" versus "1,150.53" then you will have to use the appropriate character for your "decimal point" in your input.

So...I guess I've really just expanded upon the 1st responder's answer of "use ',' instead of '.' and you'll be fine". But that's the "why" of it, potentially at least...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <p> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <br /> <br> <strike>
  • Lines and paragraphs break automatically.
  • Use <!--pagebreak--> to create page breaks.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options

CAPTCHA
Just checking to see if you're an actual person rather than a spammer. Sorry for the inconvenience.