簡體   English   中英

如何解決 java 中 hashmap 字符串拆分的數組索引越界異常?

[英]How to solve array index out of bounds exception for hashmap string split in java?

我正在嘗試將文本文件放入帶有 while 循環的 hashmap 中,並使用字符串拆分來獲取鍵值對。 但是,我在線程“main”中不斷收到異常 java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1。

package com.company;

import java.io.File;
import java.util.HashMap;
import java.util.Scanner;

public class Extract {
    public static void main(String[] args) throws Exception {
        Extract e = new Extract();
        HashMap<String, String> x = e.hashFile("locations.txt");
        x.get("name");

    }

    public HashMap<String, String> hashFile(String filename) throws Exception {
        HashMap<String, String> data = new HashMap<String, String>();

        Scanner in = new Scanner(new File(filename));
        String line;
        while (in.hasNext()) {
            line = in.nextLine();


            String[] keyvalue = line.split(":");
            keyvalue[1] = keyvalue[1].trim();


            data.put(keyvalue[0], keyvalue[1]); // this is where the exception is thrown from

        }


        in.close();
        return data;


    }


}

我的文本文件 locations.txt 看起來像:

name: Starting Point Park
exits: 1
exitDirection: E
description: You were just given your first cell phone as a birthday-present and you are at the park taking selfies. You choose your best-looking photo and upload it to your brand-new Instagram account. Suddenly, a white rabbit runs up and steals your phone and heads down a hole just big enough for you to fit in to. Instantly you panic and worry about the lost phone, not because it was a gift, but because you need to see how many likes your photo got.

為什么不試試下面看看發生了什么? 捕獲異常並打印字符串和數組。

        String[] keyvalue = null;
        try {
           keyvalue = line.split(":");
           keyvalue[1] = keyvalue[1].trim();

           data.put(keyvalue[0], keyvalue[1]); // this is where the exception is thrown from
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("line = " + line);
            System.out.println(Arrays.toString(keyvalue));
        }

暫無
暫無

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

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