Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if user input is String, double or long in Java

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();
    }

}
like image 545
user4799681 Avatar asked Apr 17 '15 06:04

user4799681


People also ask

How do you check if an input is a double or string Java?

parseDouble(stringInput); when you scan the input as a String you can then parse it to see if it is a double. But, if you wrap this static method call in a try-catch statement, then you can handle the situation where a double value is not parsed.

How do you detect if an input is a string?

Use string isdigit() method to check user input is number or string. Note: The isdigit() function will work only for positive integer numbers. i.e., if you pass any float number, it will not work. So, It is better to use the first approach.


1 Answers

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);
like image 108
TheLostMind Avatar answered Oct 07 '22 13:10

TheLostMind