I'm a beginner in java. I want to check first if the user input is String or Double or int. If it's String, double or a minus number, the user should be prompted to enter a valid int number again. Only when the user entered a valid number should then the program jump to try. I've been thinking for hours and I come up with nothing useful.Please help, thank you!
import java.util.InputMismatchException;
import java.util.Scanner;
public class Fizz {
public static void main(String[] args) {
System.out.println("Please enter a number");
Scanner scan = new Scanner(System.in);
try {
Integer i = scan.nextInt();
if (i % 3 == 0 && (i % 5 == 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i + "は3と5の倍数ではありません。");
}
} catch (InputMismatchException e) {
System.out.println("");
} finally {
scan.close();
}
}
One simple fix is to read the entire line / user input as a String.
Something like this should work. (Untested code) :
String s=null;
boolean validInput=false;
do{
s= scannerInstance.nextLine();
if(s.matches("\\d+")){// checks if input only contains digits
validInput=true;
}
else{
// invalid input
}
}while(!validInput);
You can also use Integer.parseInt and then check that integer for non negativity. You can catch NumberFormatException if the input is string or a double.
Scanner scan = new Scanner(System.in);
try {
String s = scan.nextLine();
int x = Integer.parseInt(s);
}
catch(NumberFormatException ex)
{
}
Try this one. I used some conditions to indicate the input.
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
int charCount = input.length();
boolean flag = false;
for(int x=0; x<charCount; x++){
for(int y=0; y<10; y++){
if(input.charAt(x)==Integer.toString(y))
flag = true;
else{
flag = false;
break;
}
}
}
if(flag){
if(scan.hasNextDouble())
System.out.println("Input is Double");
else
System.out.println("Input is Integer");
}
else
System.out.println("Invalid Input. Please Input a number");
Try this. It will prompt for input until an int
greater than 0 is entered:
System.out.println("Please enter a number");
try (Scanner scan = new Scanner(System.in)) {
while (scan.hasNext()) {
int number;
if (scan.hasNextInt()) {
number = scan.nextInt();
} else {
System.out.println("Please enter a valid number");
scan.next();
continue;
}
if (number < 0) {
System.out.println("Please enter a number > 0");
continue;
}
//At this stage, the number is an int >= 0
System.out.println("User entered: " + number);
break;
}
}
boolean valid = false;
double n = 0;
String userInput = "";
Scanner input = new Scanner(System.in);
while(!valid){
System.out.println("Enter the number: ");
userInput = input.nextLine();
try{
n = Double.parseDouble(userInput);
valid = true;
}
catch (NumberFormatException ex){
System.out.println("Enter the valid number.");
}
}