簡體   English   中英

線程“主”中的異常java.lang.NumberFormatException:用於輸入字符串號

[英]Exception in thread “main” java.lang.NumberFormatException: For input string number

標題是隱蔽的Bin到Dec,但是當輸入的不是二進制時會出錯。

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();
    }
}

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

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

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

if condition為false ,即用戶未輸入二進制數,則在打印消息后,控制流將到達Integer.parseInt(Bin, 2)

並根據java docs:

如果發生以下任一情況,將引發NumberFormatException類型的異常:

第一個參數為null或長度為零的字符串。

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

字符串的任何字符都不是指定基數的數字 ,除非第一個字符可以是減號'-'('\\ u002D')或加號'+'('\\ u002B')( 前提是該字符串是長於長度1。

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

您可以使用正則表達式;

 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();
}

在這里,您有一個有效的代碼:

    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();
}

您缺少if的else部分。 並且您只檢查第一個字符是0還是1,而不是整個字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM