简体   繁体   English

二进制到十进制计算器InputMismatchException

[英]Binary to Decimal calculator InputMismatchException

My goal is to create a simple binary to decimal calculator. 我的目标是创建一个简单的二进制到十进制计算器。 I try to go about this by first having the user input a string of the binary value they are trying to calculate and later use the length of this string to run a for loop (as seen in the code below). 我尝试通过首先让用户输入他们尝试计算的二进制值的字符串,然后使用此字符串的长度来运行for循环来解决此问题(如下面的代码所示)。 The calculator appears to work fine but fails when the user enters a binary number (of all 1's) longer than 20 digits. 计算器似乎可以正常工作,但是当用户输入的二进制数字(全1)超过20位时,计算器就会失败。 I receive a java.util.InputMismatchException error and I don't know how to fix it. 我收到一个java.util.InputMismatchException错误,我不知道如何解决。

public class Main {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        System.out.println("Please enter a binary number to convert to decimal: ");
        long binaryNum = scan.nextLong();
        System.out.println(binaryConverter(binaryNum));
        scan.close();

}

    public static long binaryConverter(long binaryNum) {
        String binaryString = Long.toString(binaryNum);
        long decimalValue = 0;
        for(int i = 0; i < binaryString.length(); i++) {
            if((binaryNum%10) == 0) {
                binaryNum = binaryNum/10;
            } else if((binaryNum%10) == 1) {
                decimalValue += Math.pow(2, i);
                binaryNum = binaryNum/10;
            } else {
                System.out.println("This isn't a binary number. Please try again.");
                break;
            }
        }   
        return decimalValue;
}
}

The way you want to do this to use scanner.nextLong(2) where 2 is the radix. 使用scanner.nextLong(2)的方法,其中2是基数。 Then you will be reading in an actual binary number. 然后,您将读取一个实际的二进制数。

long number = scanner.nextLong(2);
System.out.println(number);

produces 产生

144115188075855871

for input of 用于输入

111111111111111111111111111111111111111111111111111111111

If I understood you correctly you always want to convert the binary input to a decimal value. 如果我理解正确,那么您始终希望将二进制输入转换为十进制值。 A very simple solution would look like this: 一个非常简单的解决方案如下所示:

public static void main(String[] args) {
  Scanner scan = new Scanner(System.in);
  System.out.println("Please enter a binary number to convert to decimal: ");
  final String input = scan.next();
  System.out.println(Integer.parseInt(input, 2));
  scan.close();
}

If you are interested how it works under the hood, take a look at the java source for Integer.parseInt . 如果您对它的幕后工作方式感兴趣,请查看Integer.parseInt的java源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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