gpt4 book ai didi

Java数组索引越界在java中获取字符串输入时出现异常

转载 作者:太空宇宙 更新时间:2023-11-04 08:00:02 25 4
gpt4 key购买 nike

在 Java 中获取字符串输入时,出现 Java ArrayIndexOutOfBoundsException。请帮我。这是我的代码:我编辑了我的代码以使用以下方式进行分割:它说

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at solution2.Solution.main(Solution.java:27)

public class Solution {

static String search;

public static void main(String[] args){

String[] fn,ln,tp;
boolean[] isSet;
Scanner sc=new Scanner(System.in);
int no=sc.nextInt();

String[][] temp=new String[no][3];
fn=new String[no];
ln=new String[no];
tp=new String[no];
isSet=new boolean[no];
boolean flag=false;

for(int i=0;i<no;i++){
temp[i]=sc.nextLine().split(":");
fn[i]=temp[i][0];
ln[i]=temp[i][1];
tp[i]=temp[i][2];
isSet[i]=true;

}

System.out.println(temp.length);

search=sc.nextLine();

最佳答案

此行发生异常:

ln[i] = temp[i][1];

所以看起来

temp[i] = sc.nextLine().split(":");

: 分隔字符串中未收到足够的标记,无法创建大小为 3 的 String 数组。

您需要确保 temp[i].length == 3 以确保您可以分配这些 token 。

有效输入的示例(注意:没有换行符)是:

1 test:foo:bar

关于Java数组索引越界在java中获取字符串输入时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com