简体   繁体   中英

Check if input is of Primitive type in Java?

I have to check for each input and print out if it is an instance of a primitive or referenced type. But I am getting same output each time.

Note: I do search SO, but no luck. How can I check if an input is a integer or String, etc.. in JAVA?

Code:

public class Demo {

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    for(int i=0; i<9; ++i){
        String input = br.readLine();
         showPremitive(input);//check for every input
    }     
}
public static void showPremitive(Object input){
    try{
            if (input instanceof Short)
                System.out.println("Primitive : short");
            else if(input instanceof Integer)
                System.out.println("Primitive : int");
            else if(input instanceof Long)
                System.out.println("Primitive : long");
            else if(input instanceof Float)
                System.out.println("Primitive : float");
            else if(input instanceof Double)
                System.out.println("Primitive : double");        
            else if(input instanceof Boolean)
                System.out.println("Primitive : bool");
            else if(input instanceof Character)
                System.out.println("Primitive : char");
            else if(input instanceof Byte)
                System.out.println("Primitive : byte");
            else  
                System.out.println("Reference : string");
         }  
    catch (InputMismatchException e){
        System.out.println("Exception occur = "+e);
    }
}

}

Output:

Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string
Reference : string

You assign the input to a String variable. It's going to be a string.

String input = br.readLine();
//^^^ it's a string
//                  ^^^ readLine() returns String

What you are trying to achieve might not be possible using the method you have.

You're taking input using java.io.BufferedReader.readLine() .

See the documentation for BufferedReader .

public String readLine()
                throws IOException

It returns a String , regardless of what the input actually contains.

For example, "0" is a string, even though it contains a number and could be converted to an int .


One possible method (if there's a built in or existing method, I don't know it) would be to repeatedly try to convert the input to each datatype you want to check for. Then print "string" if none match. For example:

String input = br.readLine();
try{
    int i = Integer.parseInt(input);
    System.out.println("It's an int!");
}catch(Exception e){
    //well, guess not
    //do the same for all the other types
}

Here, I started with int . However, make sure you start with the most exclusive type. For example, an int can be casted to a double . Therefore, check for int first , or you could say it's a double when it can fit in an int (eg input is 5 , check that it's an integer before checking that it's a double ).

Before I address your question, you appear to have a number of misconceptions about Java and Scanner .

  1. The stuff you read from the input stream is characters or bytes. Those characters or bytes can be interpreted as representing many things ... but it is a matter of interpretation. Furthermore the same sequence of characters could mean different things ... depending on how you choose to interpret them; eg "12345" could easily be interpreted as a string, an integer or a floating point number. And if you map that to Java types, then that could be String , short , int , long , float or double ... and many more besides.

    The point is ... you (the programmer) have to tell the parser (eg Scanner ) what to expect. You can't expect it to guess (correctly).

  2. Assuming that you had managed to read as reference or (true) primitive types, you would not be able to assign them to the same variable. Integer etcetera are NOT primitive types!

  3. The Scanner.readLine() method reads and returns the rest of the current line as a String. It makes no attempt to interpret it. The Java type of the result is String ... and nothing else.


So how should you implement it. Well here's a sketch of a crude version:

     String input = br.readLine();
     showPrimitive(input);  // Note spelling!

     public void showPrimitive(String input) {
         if (input.equalsIgnoreCase("true") ||
             input.equalsIgnoreCase("false")) {
             System.out.println("Primitive : boolean");
             return;
         }
         try {
             long num = Long.parseLong(input);
             if (num >= Byte.MIN_VALUE && 
                 num <= Byte.MAX_VALUE) {
                 System.out.println("Primitive : byte");
             } else if (num >= Short.MIN_VALUE &&
                        num <= Short.MAX_VALUE) {
                System.out.println("Primitive : short");
             } else if (num >= Integer.MIN_VALUE &&
                        num <= Integer.MAX_VALUE) {
                System.out.println("Primitive : int");
             } else {
                System.out.println("Primitive : long");
             }
             return;
         } catch (NumberFormatException ex) {
             // continue
         }
         // deal with floating point (c.f. above)
         // deal with char: input length == 1
         // anything else is a String.
     }

Note that the above entails using exceptions in a way that a lot of people would object to. However, doing a better job is tricky ... if you are going to support all possible values of each of the primitive types.

But I would return to a point I made earlier. If you look at the code above, it is making hard-wired choices about how to interpret the input. But how do you know if you are making the right choices? Answer: you have to specify how the input parsing should behave ... not rely on something else to give you the "right" answer by magic.

By checking the range of each data type. Please refer following formula for calculating the range of primitive data type. -2^n-1 to +2^n-1

     int Byte=0;
     int Short=0;
     int Int=0;
     int Long=0;
     long temp=1;
     for(int i=1;i<=63;i++)
     {
        temp=temp*2;
     }
     long end=temp-1;
     long temp1=temp*2;
     temp=temp-temp1;

    Scanner sc = new Scanner(System.in);
    int t=sc.nextInt();
    
    for(int i=0;i<t;i++)
    {

        try
        {
            long x=sc.nextLong();
            System.out.println(x+" can be fitted in:");
            if(x>=-128 && x<=127)
            {
                Byte++;
            }
           if(x>=-32768 && x<=32767)
           {
               Short++;
           }
           if(x>=-2147483648 && x<=2147483647)
           {
               Int++;
           }
           if(x>=temp && x<=end)
           {
               Long++;
           }
           
           if(Byte>0 && Short>0 && Int>0 && Long>0)
           {
               System.out.println("* byte");
               System.out.println("* short");
               System.out.println("* int");
               System.out.println("* long");
               Byte=0;
               Short=0;
               Int=0;
               Long=0;
           }
           else if(Short>0 && Int>0 && Long>0)
           {
               System.out.println("* short");
               System.out.println("* int");
               System.out.println("* long"); 
               Short=0;
               Int=0;
               Long=0;
           }
           else if(Int>0 && Long>0)
           {
               System.out.println("* int");
               System.out.println("* long"); 
               Int=0;
               Long=0;
           }
           else if(Long>0)
           {
               System.out.println("* long"); 
               Long=0;
           }
           else
           {
               
           }
           
        }
        catch(Exception e)
        {
            System.out.println(sc.next()+" can't be fitted anywhere.");
        }

    }
}

Expected Output:

2
11111111
11111111 can be fitted in:
* int
* long

1
1 can be fitted in:
* byte
* short
* int
* long

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM