user9269823
user9269823

Reputation:

Exception in thread "main" java.util.InputMismatchException Using Double

import java.util.Scanner;
import java.text.DecimalFormat;

public class palomba2 {

    public static void main(String args[]) {

        Scanner keyboard = new Scanner(System.in);
        //allows input to be read
        // VOLUME OF A PRISM

        int prLngth, prWdth, prHght, prVol;

        System.out.print("Enter the length of the prism in feet: ");
        prLngth = keyboard.nextInt();

        System.out.print("Enter the width of the prism in feet: ");
        prWdth = keyboard.nextInt();

        System.out.print("Enter the height of the prism in feet: ");
        prHght = keyboard.nextInt();

        prVol = prLngth * prWdth * prHght;

        System.out.print("The volume of the prism is " + prVol);
        System.out.print(" feet.");
        System.out.println("");
        System.out.println("");
        // AREA/CIRCUMFERENCE OF A CIRCLE

        DecimalFormat format = new DecimalFormat("0.##");

        double radius, circ, area;

        System.out.print("Enter the radius of a circle rounded to the nearest hundreth: ");
        radius = keyboard.nextInt();

        circ = 2 * radius * 3.14159265358979;
        area = radius * radius * 3.14159265358979;

        System.out.print("The circumference of the circle is " + format.format(circ));
        System.out.print("units.");
        System.out.print("The area of the circle is " + format.format(area));
        System.out.print("units.");
    }
}

Everything in my code works up until I input the radius of the circle. It comes up with the error messages after I input a radius.

 Enter the radius of a circle rounded to the nearest hundreth: 2.12

 Exception in thread "main" java.util.InputMismatchException
     at java.base/java.util.Scanner.throwFor(Scanner.java:860)
     at java.base/java.util.Scanner.next(Scanner.java:1497)
     at java.base/java.util.Scanner.nextInt(Scanner.java:2161)
     at java.base/java.util.Scanner.nextInt(Scanner.java:2115)
     at palomba2.main(palomba2.java:52)

Upvotes: 1

Views: 9631

Answers (2)

oyisco
oyisco

Reputation: 1

You just have to change the:

radius = keyboard.nextInt();

to:

radius = keyboard.nextDouble();

because the variable radius is declared as double it should look like this:

double radius, circ, area;
System.out.print("Enter the radius of a circle rounded to the nearest hundreth: ");
radius = keyboard.nextDouble();

Upvotes: 0

azro
azro

Reputation: 54148

You type a double variable 2.12 but trying to read it as an int : input mismatch -> InputMismatchException


Also, the variable radius is of type double so you cannot give to it an int value (also you, you need :

  • radius = keyboard.nextDouble();

But still better to use radius = Double.parseDouble(keyboard.nextLine()) to consume the return char (same for int : int val = Integer.parseInt(keyboard.nextLine())

Upvotes: 3

Related Questions