2015-09-27 20 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 if (wrong_number == '0') digit += Math.pow(2, parameter.length() - i); 

      else 
       throw new BinaryFormatException(""); 
     } 
     return digit; 
    } 
} 
+0

正確的地方,你有'/做一個其他...'添加'否則如果(wrong_number =='0'){...}'。這將避免讓'wrong_number =='0'落入'throws'語句。 – aioobe

+0

它沒有給我正確的轉換 – agentmg123

回答

1

該程序只接受「1」爲char由於這些行:

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

既然沒有if(wrong_number == '0'),人數將只接受1和拋出一個異常當遇到0.

除此之外: 避免Math.pow,如果可能以任何方式。由於資源密集,在這種情況下完全無用。 2^x可以使用比特移位來產生一個更容易:

int pow_2_x = (1 << x); 

最後:JAVA已經爲此提供了一個method

int dec = Integer.parseInt(input_string , 2); 
+0

我在哪裏放置這些?當我刪除「Math.pow(2,parameter.length() - i);」並用「int pow_2_x =(1 << x);」代替它,它不起作用 – agentmg123

+0

@ agentmg123你不應該插入整行,只需用'1 <<替換'Math.pow ...'( parameter.length() - i - 1)'和那個'else if(wrong_number =='0')digit + = ...'語句不完全有意義。如果該位爲0,則不應添加任何內容。最簡單的解決方案是'else if(wrong_number!='0')拋出BinaryFormatException(「」);' – Paul

0

問題是與你的邏輯。由於你正在處理二進制數('1'和'0'),但你只檢查1,所以你應該檢查'0',並且只在非'0'和'1'時拋出異常。

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


else 
    throw new BinaryFormatException(""); 
+0

這根本沒有幫助。更具體一點**究竟是什麼**是這個代碼中的邏輯錯誤 – Paul

+0

@Paul我已經更新 –

相關問題