3

I am wondering how I can check if a user's input is a certain primitive type (I mean integer, String, etc... I think it's called primitive type?). I want a user to input something, then I check if it's a String or not, and do a certain action accordingly. (JAVA) I have seen some codes like this:

if (input == (String)input) { (RANDOM STUFF HERE) }

or something like

if input.equals((String) input)

And they don't work. I want to know how I can Check for only a String? (EDITED OUT) I was wondering if there was a function that can do that? Thanks for the answers

EDIT: With the help of everyone I have created my fixed code that does what I want it to:

package files;
import java.util.*;
public class CheckforSomething {
static Scanner inputofUser = new Scanner(System.in);    
static Object userInput;
static Object classofInput;
public static void main(String[] args){
    try{
    System.out.print("Enter an integer, only an integer: ");
    userInput = inputofUser.nextInt();

    classofInput = userInput.getClass();
    System.out.println(classofInput);
    } catch(InputMismatchException e) {
        System.out.println("Not an integer, crashing down");

    }

 }



 }

No need for answers anymore, thanks!

1
  • What is input? Where did it come from, and how? ie. If it is a String, then it will always be a String.. and the casts make no sense. Commented Sep 13, 2014 at 4:55

8 Answers 8

5

Use instanceof to check type and typecast according to your type:

 public class A {

    public static void main(String[]s){

        show(5);
        show("hello");
    }
    public static void show(Object obj){
        if(obj instanceof Integer){
            System.out.println((Integer)obj);
        }else if(obj instanceof String){
            System.out.println((String)obj);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This works in that context but not with a Scanner. :(
what about if I take input from stdio? I need help in this case.
3

You may try this with Regex:

String input = "34";
if(input.matches("^\\d+(\\.\\d+)?")) {
  //okay
} else {
  // not okay !
}

Here,

^\\d+ says that input starts with a digit 0-9,

()? may/or may not occur

\\. allows one period in input

Comments

1
Scanner input = new Scanner (System.in);

if (input.hasNextInt()) System.out.println("This input is of type Integer.");
else if (input.hasNextFloat()) System.out.println("This input is of type Float.");
else if (input.hasNextLine()) System.out.println("This input is of type string."); 
else if (input.hasNextDouble()) System.out.println("This input is of type Double."); 
else if (input.hasNextBoolean()) System.out.println("This input is of type Boolean.");  

  else if (input.hasNextLong())
    System.out.println("This input is of type Long."); 

Comments

1

Hate to bring this up after 6 years but I found another possible solution.

Currently attending a coding bootcamp and had to solve a similar problem. We introduce booleans and change their values depending on the result of the try/catch blocks. We then check the booleans using simple if statements. You can omit the prints and input your code instead. Here's what it looks like:

import java.io.IOException;
import java.util.Scanner;

public class DataTypeFinder {
    public static void main(String[] args) throws IOException {
        Scanner scan = new Scanner(System.in);
        String input = "";

        while (true) { //so we can check multiple inputs (optional)
            input = scan.nextLine();

            if ("END".equals(input)) { //a way to exit the loop
                break;
            }

            boolean isInt = true; //introduce boolean to check if input is of type Integer
            try { // surround with try/catch
                int integer = Integer.parseInt(input); //boolean is still true if it works
            } catch (NumberFormatException e) {
                isInt = false; //changed to false if it doesn't
            }

            boolean isDouble = true; //same story
            try {
                double dbl = Double.parseDouble(input);
            } catch (NumberFormatException e) {
                isDouble = false;
            }

            if (isInt) {
                System.out.printf("%s is integer type%n", input);
            } else if (isDouble) {
                System.out.printf("%s is floating point type%n", input);
            } else if (input.length() == 1) { //this could be useless depending on your case
                System.out.printf("%s is character type%n", input);
            } else if ("true".equals(input.toLowerCase()) || "false".equals(input.toLowerCase())) {
                System.out.printf("%s is boolean type%n", input);
            } else {
                System.out.printf("%s is string type%n", input);
            }
        }
    }
}

Comments

0
class Main{
    public static void main(String args[]){
        String str;
        Scanner sc=new Scanner(System.in);
        int n,
        boolean flag=false;
        while(!flag){
            try{
                str=sc.nextLine();
                n=Integer.parseInt(str);
                flag=true;
            }
            catch(NumberFormatException e){
                System.out.println("enter an no");
                str=sc.nextLine();
            }
        }
    }
}

Comments

-1

Is this ok?

class Test
{
    public static void main(String args[])
    {
        java.util.Scanner in = new java.util.Scanner(System.in);
        String x = in.nextLine();
        System.out.println("\n The type of the variable is : "+x.getClass());
    }
}

Output:

subham@subham-SVE15125CNB:~/Desktop$ javac Test.java 
subham@subham-SVE15125CNB:~/Desktop$ java Test
hello

 The type of the variable is : java.lang.String

Comments

-1

But Zechariax wanted an answer with out using try catch

You can achieve this using NumberForamtter and ParsePosition. Check out this solution

import java.text.NumberFormat;
import java.text.ParsePosition;


    public class TypeChecker {
        public static void main(String[] args) {
        String temp = "a"; // "1"
        NumberFormat numberFormatter = NumberFormat.getInstance();
        ParsePosition parsePosition = new ParsePosition(0);
        numberFormatter.parse(temp, parsePosition);
        if(temp.length() == parsePosition.getIndex()) {
            System.out.println("It is a number");
        } else {
            System.out.println("It is a not number");
        }
    }
}

3 Comments

This looks really good, but I'm not that advanced (Sorry) and changed my mind of the whole Try catch it looks easier than this complicated code. But thanks anyways :)
I agree Zechariax. Try catch is a simple solution. But if you don't have that option you could use this at anytime.
Ok, also is there a way to use if(randomVar = (int)) {} or something like that? That would be the most useful.
-2

Try instanceof function with Integer instead of int.. each primitive also have a class

1 Comment

Can you give more description or a code? I don't know exactly how to use it, that will help thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.