简体   繁体   中英

Need help fixing an error. Exception in thread “main” java.util.InputMismatchException

I have a program that I have be working on that converts binary to decimal. The code works for small binary numbers entered by the user but when I enter a long binary number a error happens and I get this.

Exception in thread "main" java.util.InputMismatchException: For input string: "01100101110011011010111000000101" at java.util.Scanner.nextLong(Scanner.java:2271) at java.util.Scanner.nextLong(Scanner.java:2225) at Binary.binToDec(Binary.java:30) at Driver.main(Driver.java:27)

Here is my code that has the problem.

 public void binToDec() {

    long binary;

    Scanner num = new Scanner(System.in);
    binary = num.nextLong();
    System.out.println("You entered the binary number " + binary);
    pw.println("You entered the binary number " + binary);

    long decimal = 0;
    int power = 0;

    while (true) {
        if(binary == 0) {
            break;
        } else {
            long tmp = binary % 10;
            //System.out.print("tmp: " + tmp + "\n");

            decimal += tmp * Math.pow(2, power);

            //System.out.println("decimal1: " + decimal + "\n");
            //System.out.println("power: " + power + "\n");

            binary = binary / 10;

            //System.out.println("binary: " + binary + "\n");
            power++;
        }

    }
    System.out.println("The decimal conversion is " + decimal + "\n\n");
    pw.println("The decimal conversion is " + decimal + "\n\n");
}

How do I fix this? Thanks.

使用nextLong的重载版本读取二进制输入

binary = num.nextLong(2);

It is very obvious that the value you are entering is typically going out of the range of a Long variable.

So Please try and use something like a double in your case which has far bigger range than long.

You will need to change your code a bit in order to work with double.

Hope this helps! Good Luck!

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