-3

I want to take input of number from the user and check if the number can be fit in byte, short, int, long datatypes, if user inputs extreme large number , I just display that the entered number cannot be fit in any datatype.

import java.lang.Math;
import java.util.Scanner;
class Zcheck {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String l = sc.next();
            if(l >= -128 && l <= 127)
                System.out.println(l+" can be fitted in:\n* byte\n* short\n* int\n* long");
            else if(l >= -32768 && l <= 32767)
                System.out.println(l+" can be fitted in:\n* short\n* int\n* long");
            else if(l >= -Math.pow(2, 31) && l <= (Math.pow(2, 31) - 1))
                System.out.println(l+" can be fitted in:\n* int\n* long");
            else if(l >= -Math.pow(2, 63) && l <= (Math.pow(2, 63) - 1))
                System.out.println(l+" can be fitted in:\n* long");
            else
                System.out.println(l+" can't be fitted anywhere.");
        }
    }
}

Things were okk when the user inputs a number which can be store in long type I just make long variable and comparing it with the with the ranges of datatypes and display the appropriate message using if-else. But when the user inputs extremly large number it was the problem that I cannot store such large number in long data type too. So I tried for String or BigInteger data types but further the problem occurred that I cannot compare String or BigInteger with the another datatype in if-else condition.

  • 2
    You tried with BigInteger and failed? What did you try? How did it fail? – khelwood Sep 27 '21 at 13:29
  • "_it failed to compare BigInteger with Integer value_" You shouldn't compare BigIntegers objects with `>`. Use `.compareTo()` to compare them. Like `if (new BigInteger(str).compareTo(BigInteger.valueOf(2).pow(63)) > 0)`. – Ivar Sep 27 '21 at 14:13

1 Answers1

-1

You can't compare Strings to numbers using < and >. To the computer, the string "127" is not a number at all. It's like asking someone "is apple bigger than 5?" It's not a solvable question.

You said you are working with "extremely large" numbers, although 127 isn't very large at all. But assuming this is true, you'll want to parse the string into a long first, then compare. This explains how to do it quite well.

Also, this code isn't taking user input at all. Do you also need help on that, or have you simply not implemented it yet?

Gummysaur
  • 96
  • 7
  • 1
    It's hard to know from the vagueness of the question, but long is not guaranteed to cover an "extremely large" number either. – khelwood Sep 27 '21 at 13:34
  • I have edited my question for proper understanding. see that if you could solve my doubt – Mohit Rajgor Sep 27 '21 at 14:01