【问题标题】:How to get the last number of an integer input如何获取整数输入的最后一个数字
【发布时间】:2017-09-07 16:43:45
【问题描述】:

不使用内置 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));
    }

}

【问题讨论】:

  • 请尽量减少问题,直到它是minimal reproducible example
  • “整数输入的最后一个数字”是指数字吗?如果您只输入少于或多于 8 位会怎样?
  • 是的,我输入的 int 的最后一位数字
  • 我运行了你的代码,没有任何异常...
  • 你可能有一个前导 0 被 parseInt() 忽略。

标签: java exception int number-formatting


【解决方案1】:

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

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

【讨论】:

  • 感谢帮助的朋友!
【解决方案2】:

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

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);

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2019-12-08
    • 2015-01-29
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多