不使用内置 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));
}
}
最佳答案
解析和格式化 int
时,前导零将被忽略。最简单的解决方案是将完整值保留为字符串,然后才解析各个数字:
String binary = keyboard.next();
int firstDigit = Integer.parseInt(binary.substring(0, 1));
// etc.
关于java - 如何获取整数输入的最后一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46101469/