簡體   English   中英

使用分隔符將字符串數組轉換為int

[英]Converting string array to int with a delimiter

我無法弄清楚為什么我得到一個空指針異常。 我正在嘗試轉換用戶在提示后輸入的行號,並且我想要將其標記為空格“”逗號“,”或逗號和空格“,”。

這是我的代碼,我在nums [i] = Integer.parseInt(holder [i])上得到一個空指針異常; 線。 我只是想不通為什么。

String again="n";
    int[] nums = null;

    do {
        Scanner scan = new Scanner (System.in);

        System.out.println("Enter a sequence of integers separated by a combination of commas or spaces: ");
        String in=scan.nextLine();
        String[] holder=in.split(",| |, ");

            for (int i=0; i<holder.length; i++) {

                nums[i]=Integer.parseInt(holder[i]);
                System.out.print(nums[i]);
            }


    }
    while (again=="y");

好的感謝大家,我通過將nums數組的長度初始化為持有者數組的長度來實現它,如接受的答案中所建議的那樣。 像這樣:

int[] nums = new int[holder.length];

我有第二個問題,因為我的正則表達式似乎失敗了,如果用“,”或“”而不是“,”任何想法描述,我可以讀它嗎?

這是我的錯誤:

Enter a sequence of integers separated by a combination of commas or spaces: 
    1, 2, 3
    Exception in thread "main" 1java.lang.NumberFormatException: For input string: ""
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at SortComparison.main(SortComparison.java:20)

您的空指針異常是由於您已將nums數組初始化為null,然后嘗試在for循環中“指向”它而引起的。 您可以丟失int[] nums = null並添加:

int[] nums = new int[holder.length];

緊接在for循環之前(顯然你創建了holder數組之后)。

你已經設定好了

int[] nums = null;

然后嘗試訪問

num[i]

這會給你NullPointerException。 首先需要構造數組以保存所需數量的元素:

int[] nums = new int[holder.length] 

你最好打印你的holder[i]然后再將其解析為整數,看看里面有什么。 我猜測holder[i]沒有Integer的有效值。

暫無
暫無

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

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