標題是將Bin轉換爲Dec,但輸入非二進制文件時出錯。線程「主」java.lang.NumberFormatException中的異常:對於輸入字符串編號
public class Bin2Dec {
public static void main(String[] args) {
String bin;
Scanner in = new Scanner(System.in);
System.out.println("enter a binary number: ");
bin = in.next();
//BinLen = Bin.length();
char n=bin.charAt(0);
if(n != 1 && n != 0){
System.out.println("You did not enter a binary number.");
}
int decimalValue = Integer.parseInt(Bin, 2);
System.out.println("Bin= " + bin + " convert to Dec= " + decimalValue);
in.close();
}
}
是嗎?當輸入不是二進制時,你期望'parseInt()'做什麼? – Andreas
對,那麼你期望*它有什麼行爲?你目前正在檢查第一個字符,但這就是全部 - 而且你也沒有正確檢查,因爲你應該檢查「1」和「0」而不是1和0.(你是在檢測到錯誤之後,也不會放棄將其轉換的嘗試......) –