checking the input for primitive data types in java

I was given to code a program that would take input of a number and check, in which all primitive data types(byte, short, int, long) it will fit in. I wrote the following code but it is not passing all the test cases:

import java.util.*;
import java.io.*;


class Solution {
    public static void main(String []args) {
        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>=-Byte.MAX_VALUE && x<=Byte.MAX_VALUE)
                    System.out.println("* byte");
                if(x>=-Short.MAX_VALUE && x<=Short.MAX_VALUE)
                    System.out.println("* short");
                if(x>=-Integer.MAX_VALUE && x<=Integer.MAX_VALUE)
                    System.out.println("* int");
                if(x>=-Long.MAX_VALUE && x<=Long.MAX_VALUE)
                    System.out.println("* long");                
            }
            catch(Exception e) {
                System.out.println(sc.next()+" can't be fitted anywhere.");
            }
        }
    }
}

3 Answers

Of course it’ll fail. Take a byte. In Java, it is represented as a signed 8bit value (2’s complement notation). It means its range varies from -128 to +127. You logic says that it’ll be a byte if it lies b/w (inclusive of both sides), -127 to +127. It’ll fail for -128.

Replace -Byte.MAX_VALUE with Byte.MIN_VALUE and it’ll work.

You should be using ifelse logic here, to prevent a given input from matching more than one case:

long x = sc.nextLong();
System.out.println(x+" can be fitted in:");
if (x >= Byte.MIN_VALUE && x <= Byte.MAX_VALUE) {
    System.out.println("* byte");
}
else if (x >= Short.MIN_VALUE && x <= Short.MAX_VALUE) {
    System.out.println("* short");
}
else if (x >= Integer.MIN_VALUE && x <= Integer.MAX_VALUE) {
    System.out.println("* int");
}
else if (x >= Long.MIN_VALUE && x <= Long.MAX_VALUE) {
    System.out.println("* long");
}
else {
    System.out.println("value does not fit any type");
}

I hope if you give a value which can’t be taken by a long variable, the value will wrap around between Long.MAX_VALUE & Long.MIN_VALUE. What i can suggest is, get the input as a string from the user and construct BigDecimal and compare the range values of the primitives with the BigDecimal Values using some builtin methods.

Archive from: https://stackoverflow.com/questions/59064051/checking-the-input-for-primitive-data-types-in-java

Leave a Reply

Your email address will not be published. Required fields are marked *