I'm a beginner at java and there's something puzzling me about my code, In the assignment i'm supposed to, as the assignment requests: "Make sure the user has entered a valid integer value. Write an if() statement as follows: Use the Scanner hasNextInt() method in the logical expression to get a Boolean value" but whenever I insert the Input(Scanner name).hasNextInt as the if statements logical expression my console does not print the factorial. What im a supposed to do in order to be able to use the hasNextInt method properly.
import java.util.Scanner;
public class Factorials {
public static void main(String[] args) {
// TODO Auto-generated method stub
//1. create variables
int num = 0;
//2. Input prompt
Scanner Input = new Scanner(System.in);
System.out.print("Please enter a number that is an integer: ");
num = Input.nextInt();
if (Input.hasNextInt()) {
long fact = 1;
for (int i = 2; i <= num; i++) {
fact = fact * i;
}
System.out.println("");
System.out.println("The factorial of "+num+" is: "+fact);
Input.close();
return;
}
else {
System.out.println("The text you entered was either not a number or is not an integer, please try again.");
Input.close();
return;
}// end of if
}// end of main
}// end of class
Aucun commentaire:
Enregistrer un commentaire