I have to write the code to (first) check if the user's input is a number, if it isn't, print "Invalid input." (Second) If it's a number, check again if it's a non-zero number, print "Invalid input" again if it isn't.
I've got the second part figured out but I can't seem to have the first part working aka check if the input is a number. I would have to enter 2 inputs instead of one and if the first input is not a number, java would give me an error instead of printing "Invalid input".
Scanner stdin = new Scanner(System.in);
System.out.println("Enter a non-zero number");
double number = stdin.nextDouble();
if (stdin.hasNextDouble()) {
if(number != 0) {
System.out.println("Reciprocal is " + 1 / number);
}
else {
System.out.println("Invalid input");
}
}
else {
System.out.println("Invalid Input");
}
Aucun commentaire:
Enregistrer un commentaire