2016-11-21 55 views
-1

標題是將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(); 
    } 
} 
+1

是嗎?當輸入不是二進制時,你期望'parseInt()'做什麼? – Andreas

+0

對,那麼你期望*它有什麼行爲?你目前正在檢查第一個字符,但這就是全部 - 而且你也沒有正確檢查,因爲你應該檢查「1」和「0」而不是1和0.(你是在檢測到錯誤之後,也不會放棄將其轉換的嘗試......) –

回答

0

在這裏你有一個工作代碼:

String Bin; 
    Scanner in = new Scanner(System.in); 
    System.out.println("enter a binary number: "); 
    Bin = in.next(); 
    // BinLen = Bin.length(); 
    for (int i = 0; i < Bin.length(); i++) { 
     char n = Bin.charAt(i); 
     if (n != '1' && n != '0') { 
      System.out.println("You did not enter a binary number."); 
      System.exit(0); 
     } 
    } 

     int decimalValue = Integer.parseInt(Bin, 2); 
     System.out.println("Bin= " + Bin + " convert to Dec= " + decimalValue); 
     in.close(); 
} 

你缺少的,如果其他部分。而你只檢查的第一個字符是0或1,而不是整個字符串

+1

您可能應該在'else'之外保留'close()',並刪除多餘的'}'。 – Andreas

1

你的這部分代碼是罪魁禍首:

if(n != 1 && n != 0) { 
    System.out.println("You did not enter a binary number."); 
} 

int decimalValue = Integer.parseInt(Bin, 2); 

if條件false,即用戶不輸入的二進制數,打印信息後控制流程將達到Integer.parseInt(Bin, 2)

和按Java文檔:

第一個參數是空值或零長度的字符串:

如果發生以下任一情況NumberFormatException類型的則拋出異常。

基數小於Character.MIN_RADIX或大於Character.MAX_RADIX。

除第一個字符可能是減號' - '('\ u002D')或加號'+'('\ u002B')外,字符串的任何字符都不是指定基數的數字。 )假設字符串比長度1長。

字符串表示的值不是int類型的值。

1

您可以使用正則表達式;

if (! Bin.matches("[01]+")) { 
    System.out.println("You did not enter a binary number"); 
    System.exit(0); 
}else{ 
    int decimalValue = Integer.parseInt(Bin, 2); 
    System.out.println("Bin= " + Bin + " convert to Dec= " + decimalValue); 
    in.close(); 
} 
相關問題