如何获取整数输入的最后一个数字

问题描述 投票:1回答:2

二进制到十进制转换器,不使用内置的Java方法。它必须自动执行此转换。当我在输入期间获得整数的最后一个数字时,它给出了一个数字格式异常。

import java.util.Scanner;

public class Homework02 {

    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);

        System.out.println("Enter an 8-bit binary number:");
        int binary = keyboard.nextInt();
        int copyBinary = binary;
        int firstDigit = Integer.parseInt(Integer.toString(copyBinary).substring(0, 1));
        int secondDigit = Integer.parseInt(Integer.toString(copyBinary).substring(1, 2));
        int thirdDigit = Integer.parseInt(Integer.toString(copyBinary).substring(2, 3));
        int fourthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(3, 4));
        int fifthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(4, 5));
        int sixthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(5, 6));
        int seventhDigit = Integer.parseInt(Integer.toString(copyBinary).substring(6, 7));
        int eigthDigit = Integer.parseInt(Integer.toString(copyBinary).substring(7));

        firstDigit = firstDigit*128;
        secondDigit = secondDigit*64;
        thirdDigit = thirdDigit*32;
        fourthDigit = fourthDigit*16;
        fifthDigit = fifthDigit*8;
        sixthDigit = sixthDigit*4;
        seventhDigit = seventhDigit*2;
        eigthDigit = eigthDigit*1;

        System.out.println(firstDigit+" "+secondDigit+" " +thirdDigit+" "+fourthDigit+" "+fifthDigit+" "+sixthDigit+" "+seventhDigit+" "+eigthDigit);

        System.out.println(copyBinary + " in decimal form is " + (firstDigit+secondDigit+thirdDigit+fourthDigit+fifthDigit+sixthDigit+seventhDigit+eigthDigit));
    }

}
java exception int number-formatting
2个回答
1
投票

在解析和格式化int时,将忽略前导零。最简单的解决方案是将完整值保持为字符串,然后才解析各个数字:

String binary = keyboard.next();
int firstDigit = Integer.parseInt(binary.substring(0, 1));
// etc.

0
投票

我在评论中提出的是将整个输入读作字符串,然后将一个字符转换为整数

Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an 8-bit binary number:");
String input = keyboard.nextLine();
// need to validate input here
int dec = 0;
for (int i=0; i<input.length(); i++) {
   int x = Character.getNumericValue(input.charAt(input.length()-1-i));
   dec += x * Math.pow(2, i);
}
System.out.println("For binary number " + input + " its decimal value is "  + dec);
© www.soinside.com 2019 - 2024. All rights reserved.