【问题标题】:Why my binary to decimal conversion program doesn't read 0s?为什么我的二进制到十进制转换程序不读取 0?
【发布时间】:2015-09-25 13:58:33
【问题描述】:

这个程序应该将二进制数转换为十进制,并在输入有非二进制数时抛出异常。这个程序会读取 1,但是当我输入 0 时,它会抛出异常并告诉我它不是二进制的。

测试程序:

   //Prepare scanner from utility for input.
   import java.util.Scanner;

   public class Bin2Dec {
       public static void main (String[] args){
       //Convert the input string to their decimal equivalent.
        //Open scanner for input.
        Scanner input = new Scanner(System.in);
        //Declare variable s.
        String s;

        //Prompt user to enter binary string of 0s and 1s.
        System.out.print("Enter a binary string of 0s and 1s: ");
        //Save input to s variable.
        s = input.nextLine();
            //With the input, use try-catch blocks.
            //Print statement if input is valid with the conversion.
            try {
             System.out.println("The decimal value of the binary number "+ "'" + s + "'" +" is "+conversion(s));
             //Catch the exception if input is invalid.
              } catch (BinaryFormatException e) {
                  //If invalid, print the error message from BinaryFormatException.
                System.out.println(e.getMessage());
              }
            }
          //Declare exception.
          public static int conversion(String parameter) throws BinaryFormatException {
            int digit = 0;
            for (int i = parameter.length(); i > 0; i--) {
              char wrong_number = parameter.charAt(i - 1);
              if (wrong_number == '1') digit += Math.pow(2, parameter.length() - i);
              //Make an else statement and throw an exception.
              else 
                  throw new BinaryFormatException("");
            }
            return digit;
          } 
        }

异常程序:

    public class BinaryFormatException extends Exception {
        //Declare message.
          private String message;
          public BinaryFormatException(String msg) {
            this.message = msg;
          }
          //Return this message for invalid input to Bin2Dec class.
          public String getMessage() {
             return "Error: This is not a binary number";
          }
        }

【问题讨论】:

  • ...因为你告诉它? if(wrong_number == '1') {/*do stuff*/} else throw new BinaryFormatException();

标签: java exception binary decimal


【解决方案1】:

如果 char 不是 1,则会引发 BinaryFormatException 异常。

       if (wrong_number == '1') digit += Math.pow(2, parameter.length() - i);
          //Make an else statement and throw an exception.
          else 
              throw new BinaryFormatException("");

【讨论】:

    【解决方案2】:

    如果 char 不是 1,您将抛出 BinaryFormatException 异常。

    if (wrong_number =='1') -> if (wrong_number =='1' || wrong_number=='0')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-16
      • 1970-01-01
      • 2019-05-05
      • 2020-12-07
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多