Search code examples
javainputdouble

scanner skips double type numbers


Hello I'm new in java and as i was making a program practicing input/output methods I came to this error:

When I input a int value the program works well, but when I input a double value it shows me this:

enter image description here

Here is my code:

import java.util.Scanner;

public class InpOutp
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);  // creates a scanner

        System.out.print("Enter price of a six-pack beer: ");
        double packPrice = in.nextDouble();

        System.out.print("Give the ml of a can: ");
        double canMl = in.nextDouble();

        final double CANS_PER_PACK = 6;
        double packMl = canMl * CANS_PER_PACK;

        // find the price per ml of a pack
        double pricePerMl = packPrice / packMl;
        System.out.printf("Price per ml: %8.3f", pricePerMl);
        System.out.println();
    }
}

Solution

  • The problem is the separator. If you wish to use period try this

    Scanner in = new Scanner(System.in).useLocale(Locale.US);
    

    EDIT:

    Also it is worth to mention, you should use in.nextLine(); after every nextInt() or nextDouble() otherwise you will encoder problems with nextLine when entering text.

    Try this

        System.out.print("Enter price of a six-pack beer: ");
        double packPrice = in.nextDouble();
        System.out.println("this will be skipped" +  in.nextLine());
    
        System.out.print("Give the ml of a can: ");
        double canMl = in.nextDouble();
        in.nextLine();
        System.out.print("And now you can type: ");
        System.out.println(in.nextLine());