[英]Putting names and numbers from a text file into arrays
这里有一个等级,名称和受欢迎程度的列表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)
任何帮助都是极好的! 谢谢
由于名称数组的长度为1,因此名称的最大索引为0。因此,在下一次循环迭代中,当i = 1时,此行将超出范围。
name[i] = inputStream.next();
乍一看,您正在创建大小为1的数组( new int[1]
等),然后尝试在for循环中访问索引0-999。 如果您希望数组中有1000个位置(如for循环所需),则应创建一个数组,例如new int[1000]
。
您已经将name
初始化为大小为1的数组,但是随后引用了name[i]
,其中i
最多计数1000。name name[0]
起作用,但是一旦到达name[1]
,您就会得到异常。
您应该将name
初始化为String[1000]
。 或者(更好)使用ArrayList,它会在您向其中添加项目时扩展。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.