简体   繁体   中英

Putting names and numbers from a text file into arrays

There is a list of ranks, names, and popularity 1 Jake 21021 (rank, the actual name, how many babies were given that name that year) I am trying to take these three separate things, and divide them up into arrays. That way if a user searches for "Jake" rank: 1 pops up and so does 21021. This is what i have so far...

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 ;
        }
    }
}

i keep getting an error

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

any help would be awesome! thanks

由于名称数组的长度为1,因此名称的最大索引为0。因此,在下一次循环迭代中,当i = 1时,此行将超出范围。

name[i] = inputStream.next(); 

At a glance, you're creating arrays of size 1 ( new int[1] , etc), and then trying to access indexes 0-999 inside your for loop. If you want an array to have 1000 positions in it, like your for loop requires, then you should create an array such as new int[1000] .

You've initialized name as an array of size 1, but then you reference name[i] , where i is counting up to 1000. name[0] works, but as soon as you reach name[1] , you get the exception.

You should initialize name as String[1000] . Or (better yet) use an ArrayList, which expands as you add items to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM