gpt4 book ai didi

java - 将文本文件中的姓名和数字放入数组中

转载 作者:行者123 更新时间:2023-12-02 00:24:30 27 4
gpt4 key购买 nike

有一个排名、名称和受欢迎程度的列表 1 Jake 21021(排名、实际名称、当年有多少婴儿被赋予这个名字)我试图将这三个单独的东西分成数组。这样,如果用户搜索“Jake”排名:1 就会弹出,21021 也会弹出。这就是我到目前为止所拥有的...

import java.util.*;
import java.io.*;

public class Test
{
public static void main(String[] args)

{
Scanner inputStream = null;
try
{
inputStream = new Scanner(new FileInputStream("src/boynames.txt"));
}
catch (FileNotFoundException e)
{
System.out.println("Sorry we couldn't find the requested file...");
System.out.println("Exiting...");
System.exit(0);
}
//Initializing the BOY Variables
int[] counter = new int[1];
String[] name = new String[1];
int[] popularity = new int[1];
//End of initializing BOY variables
for (int i=0; i <1000;i++)
{
counter[0] = 1;
name[i] = inputStream.next();
popularity[i]=inputStream.nextInt();
System.out.print(counter[i] + " " + name[i] + " " + popularity[i] );
counter[i] = counter[i] + 1 ;
}
}
}

我不断收到错误

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

任何帮助都会很棒!谢谢

最佳答案

您已将 name 初始化为大小为 1 的数组,但随后引用了 name[i],其中 i 正在向上计数到 1000。name[0] 有效,但是一旦到达 name[1],就会出现异常。

您应该将name初始化为String[1000]。或者(更好)使用 ArrayList,当您向其中添加项目时,它会扩展。

关于java - 将文本文件中的姓名和数字放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10290936/

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