該程序應該將二進制數轉換爲十進制數,並在輸入非二進制數時引發異常。這個程序會讀取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;
}
}
正確的地方,你有'/做一個其他...'添加'否則如果(wrong_number =='0'){...}'。這將避免讓'wrong_number =='0'落入'throws'語句。 – aioobe
它沒有給我正確的轉換 – agentmg123