Reputation: 67
Im trying to make sure the user is inputing a number and not a word. How would I do this? I tried this, but when I type in numbers it still says that it is a string.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("What is the diameter of the sphere (cm): ");
var diameter = input.next();
if (diameter instanceof String) {
System.out.println("Please enter a number");
} else {
break;
}
}
}
}
Upvotes: 0
Views: 1961
Reputation: 67
".next()" is a string. If you want a double use ".nextDouble". Instead of using if statements, use a try catch which will catch an exception if the user enters the wrong data type.
import java.util.*;
import java.util.InputMismatchException;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double diameter;
while (true) {
System.out.print(
"What is the diameter of the sphere (cm): ");
try {
diameter = input.nextDouble();
break;
} catch (InputMismatchException mme) {
System.out.println("double value not entered");
// clear the scanner input
input.nextLine();
}
}
System.out.println("The diameter is " + diameter);
}
}
Credit: @WJS
Upvotes: 0
Reputation: 2890
Every keyboard input is a string at fist. If you need a number, you need to convert it. Since you're using a scanner, input.nextInt()
would do that for you (and throw an exception if the input isn't parseable as a number). There's also input.hasNextInt()
, which will consume some input and tell you whether it's an integer, in which case nextInt()
won't throw.
You can also use Integer.parseInt()
to convert a String
into an integer (again, this will throw an exception if the input isn't a number).
(There are of course also corresponding versions of these functions for the other numeric types)
Upvotes: 0
Reputation: 10936
Incorrect input will throw an exception of the type InputMismatchException
when called with the input.next*
family of functions (Boolean, Byte, Double, Float, Int, Line, Long, Short).
If you are expecting a specific type, use that version of the function and wrap it in a try-catch block with:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
while(true) {
System.out.println("What is the diameter of the sphere (cm): ");
try {
var diameter = input.nextFloat();
break;
} catch(InputMismatchException e) {
System.out.println("Please enter a number");
}
}
}
See https://www.w3schools.com/java/java_user_input.asp
Upvotes: 1