Java ArrayList IndexOutOfBoundsException索引:1,大小:1

编程入门 行业动态 更新时间:2024-10-19 08:45:21
本文介绍了Java ArrayList IndexOutOfBoundsException索引:1,大小:1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试用Java读取某个文件并将其转换为多维数组。每当我从脚本中读取一行代码时,控制台都会说:

I'm attempting to read a certain file in Java and make it into a multidimensional array. Whenever I read a line of code from the script, The console says:

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

我知道这个错误是在编码无法达到具体目的时引起的索引,但我现在还不知道如何修复它。

I know that this error is caused when the coding can't reach the specific index, but I have no idea how to fix it at the moment.

这是我编码的一个例子。

Here is an example of my coding.

int x = 1; while (scanner.hasNextLine()) { String line = scanner.nextLine(); //Explode string line String[] Guild = line.split("\\|"); //Add that value to the guilds array for (int i = 0; i < Guild.length; i++) { ((ArrayList)guildsArray.get(x)).add(Guild[i]); if(sender.getName().equals(Guild[1])) { //The person is the owner of Guild[0] ownerOfGuild = Guild[0]; } } x++; }

**文本文件**

Test|baseman101|baseman101|0| Test2|Player2|Player2|0|

其他解决方案,例如:写入文本文件而不用Java覆盖

Other solutions, such as the one found here: Write to text file without overwriting in Java

在此先感谢。

推荐答案

问题1 - > int x = 1; 解决方案:x应该从0开始

problem 1 -> int x = 1; solution: The x should be start with 0

问题2->

((ArrayList)guildsArray.get(x)).add(Guild[i]);

您正在增加 x 所以 if x> = guildsArray.size()然后你会得到 java.lang.IndexOutOfBoundsException

You are increasing x so if x >= guildsArray.size() then you will get java.lang.IndexOutOfBoundsException

解决方案

if( x >= guildsArray.size()) guildsArray.add(new ArrayList()); for (int i = 0; i < Guild.length; i++) { ((ArrayList)guildsArray.get(x)).add(Guild[i]); if(sender.getName().equals(Guild[1])) { //The person is the owner of Guild[0] ownerOfGuild = Guild[0]; } }

更多推荐

Java ArrayList IndexOutOfBoundsException索引:1,大小:1

本文发布于:2023-11-22 20:34:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1618921.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:索引   大小   Java   ArrayList   IndexOutOfBoundsException

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!