2015-09-25 54 views
0

該程序應該將二進制數轉換爲十進制數,並在輸入非二進制數時引發異常。這個程序會讀取1,但是當我輸入0時,它會拋出異常並告訴我它不是二進制的。爲什麼我的二進制到十進制轉換程序不讀取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"; 
      } 
     } 
+0

......因爲你告訴它? 'if(wrong_number =='1'){/ * do stuff * /} else throw new BinaryFormatException();' – immibis

回答

1

你扔BinaryFormatException異常,如果char是一個也沒有。

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

如果字符不是一個,則拋出BinaryFormatException異常。

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

相關問題