Sam Shaheen
Sam Shaheen

Reputation: 35

Using a scanner in Java

I'm working on a Java assignment and whenever I insert a decimal into my scanner, the code returns errors. I went far enough to realize that it wasn't because the number was a decimal, but because whenever any character that is not a number is entered this error is returned.

Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at population.main(population.java:14)

If anyone can help me get decimals to work that would be cool, here is my bad code.

import java.util.Scanner;

public class population {

    public static void main(String[] args) {
        System.out.print("Enter the amount of years:"); // Prompts the user
        Scanner input = new Scanner(System.in); // Defines the scanner
        double value = input.nextInt(); // Defines the variable


        double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
        double B = ((60.0 / 7.0) * A); // Births per year
        double C = ((60.0 / 13.0) * A); // Deaths per year
        double D = ((60.0 / 45.0) * A); // Immigration per year
        double E = (B + D - C); // Change per year  
        double F = ((E * value) + 312032486.0); // Change in population after 5 years

        System.out.println(F);

    }

}

Upvotes: 0

Views: 110

Answers (3)

Kumar
Kumar

Reputation: 4010

Exception occur because of invalid input. you can add try catch block. See the below code.
For More information see this

public static void main(String[] args) {
    try
    {
        System.out.print("Enter the amount of years:"); // Prompts the user
        Scanner input = new Scanner(System.in); // Defines the scanner
        double value = input.nextInt(); // Defines the variable
        double A = (60.0 * 24.0 * 365.0); // Brings time from seconds to years
        double B = ((60.0 / 7.0) * A); // Births per year
        double C = ((60.0 / 13.0) * A); // Deaths per year
        double D = ((60.0 / 45.0) * A); // Immigration per year
        double E = (B + D - C); // Change per year  
        double F = ((E * value) + 312032486.0); // Change in population after 5 years
        System.out.println(F);
    }
    catch(Exception e)
    {
        System.out.println("Invalid Input");
    }
}

Upvotes: 0

SparkOn
SparkOn

Reputation: 8956

Scanner#nextInt()- Scans the next token of the input as an int.

and throws InputMismatchException - if the next token does not match the Integer regular expression, or is out of range

input.nextInt() takes an input of type int

use

input.nextDouble()

Upvotes: 0

venkatKA
venkatKA

Reputation: 2399

input.nextInt(); accepts an integer. Change it into input.nextDouble()

Upvotes: 2

Related Questions