I'm a complete beginner and trying to write a code to print the factorial of a number. I want the user to be able to enter any possible number they want, but if they enter a number that is not a positive integer, the program tells them they have to try again. But when I run the code and try entering '5.5', I get a compilation error. I cannot figure out why. What is going wrong?
package javaExercises;
import java.util.Scanner;
public class Fac {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
try {
double result = 1; //initialize our result variable
System.out.println("Enter a positive integer: ");
double fac = in.nextDouble();
if (fac != (int) fac)
System.out.println("Your entry is not an integer.");
else if (fac < 0)
System.out.println("Your entry is negative.");
else if (fac == 0)
System.out.println("The factorial of 0 is 1.");
else {
for (double i = fac; i > 1; i--)
result *= i;
System.out.println("The factorial of " + Math.round(fac) + " is " + Math.round(result) + ".");
}
} finally {
in .close();
}
}
}
The error I am getting:
Enter a positive integer: 4.5 Exception in thread "main"
java.util.InputMismatchException at
java.base/java.util.Scanner.throwFor(Scanner.java:939) at
java.base/java.util.Scanner.next(Scanner.java:1594) at
java.base/java.util.Scanner.nextDouble(Scanner.java:2564) at
javaExercises.Fac.main(Fac.java:16) –