简体   繁体   English

如何解决 java 中 hashmap 字符串拆分的数组索引越界异常?

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

I am trying to put a text file into a hashmap with a while loop, and use string split to get the key value pairs.我正在尝试将文本文件放入带有 while 循环的 hashmap 中,并使用字符串拆分来获取键值对。 However, I keep getting Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 1 out of bounds for length 1.但是,我在线程“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;


    }


}

My text file locations.txt looks like:我的文本文件 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.

Why not try the following to see what is going on?为什么不试试下面看看发生了什么? Catch the exception and print the string and the array.捕获异常并打印字符串和数组。

        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