Receiving float from Scanner input Java
Since you're using nextFloat()
you must be sure that you enter a floating number, otherwise clear the scanner with next()
public static void main(String[] args) throws Exception {
while (true) {
System.out.print("Enter a float: ");
try {
float myFloat = input.nextFloat();
if (myFloat % 1 == 0) {
throw new Exception("Wrong type");
}
System.out.println(myFloat);
} catch (InputMismatchException ime) {
System.out.println(ime.toString());
input.next(); // Flush the buffer from all data
}
}
}
Results:
UPDATE
You still have to handle the InputMismatchException, just throw your own exception in the catch block.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// while (true) just for testing
while (true) {
try {
System.out.print("Enter a float: ");
System.out.println(CheckFloat(input));
} catch (MyException me) {
System.out.println(me.toString());
}
}
}
private static float CheckFloat(Scanner sc) throws MyException {
try {
float input = sc.nextFloat();
if (input % 1 == 0) {
throw new MyException("Wrong type");
} else {
return input;
}
} catch (InputMismatchException ime) {
sc.next(); // Flush the scanner
// Rethrow your own exception
throw new MyException("Wrong type");
}
}
private static class MyException extends Exception {
// You exception details
public MyException(String message) {
super(message);
}
}
Results:
Kala
Updated on November 28, 2022Comments
-
Kala over 1 year
I need a method that should check whether user's input is a float, and if it is string or int it should throw an exception.
I declare the Scanner outside of the method:
Scanner sc = new Scanner(System.in);
And the method definition is:
private boolean CheckFloat(Scanner sc) throws MyException { if(!sc.hasNextFloat()){ throw new MyException("Wrong type"); } else { float input = sc.nextFloat(); if(input%1==0) { throw new MyException("Wrong type"); } else return true; } }
The problem is that the exception is thrown no matter what the user types in, so my question is: what exactly do I do wrong?
I know that in Java an input like 1.2 is interpreted as double, but how to take a float from the console then? Or do I misunderstand working of the method hasNextFloat() or the whole Scanner?
I haven't found anything helpful so far
-
JeramyRR almost 9 yearsYou may need to make a call to sc.next() before your !sc.hasNextFloat()
-
-
Kala almost 9 yearsOk sorry I'm tired :p But for me it still throws exception also when I give the proper float input
-
Kala almost 9 yearsAs I corrected my code I noticed that it also accepted only the comma notation, and that's why your solution didn't work for me properly... So I guess I should just change the locale now. Sorry and thanks a lot for help anyway