Matic
Matic

Reputation: 501

Why does Java outputs decimal number as Integer?

So here is my program:

// Creates a Scanner object that monitors keyboard input
static Scanner userInput = new Scanner(System.in);

public static void main(String[] args)
{

    System.out.print("How old are you? ");

    int age = checkValidAge();

    if (age != 0)
    {
    System.out.println("You are " + age + " years old");
    }

}

public static int checkValidAge() 
{

    try
    {
        return userInput.nextInt(); // nextInt() receives the user input
    }

    catch (InputMismatchException e)
    {
        userInput.next(); // Skips the last user input and waits for the next
        System.out.print("That isn't a whole number");
        return 0;
    }

}

When I enter a number with 3 decimal places, Java outputs it as an Integer:

enter image description here

If I input the number with 2 or more than 3 decimal points, then the program will know that input is not correct. So why does it ignore 3 decimal places and outputs it as an int?

Upvotes: 0

Views: 398

Answers (1)

Gorazd Rebolj
Gorazd Rebolj

Reputation: 825

Stream::nextInt reads an integer from a stream.
2,444 is an integer in your default locale (2,444 = 2444).

If you want to read a decimal number you need to use the Stream::nextDouble or another appropriate method.

Upvotes: 1

Related Questions