简体   繁体   中英

Java, Reading two different types of variables from a file and using them as objects later

I working on a project that is based on reading a text from a file and putting it as objects in my code.

My file has the following elements: (ignore the bullet points)

  • 4
  • Christmas Party
  • 20
  • Valentine
  • 12
  • Easter
  • 5
  • Halloween
  • 8

The first line declares how many "parties" I have in my text file (its 4 btw) Every party has two lines - the first line is the name and the second one is the number of places available.

So for example, Christmas Party has 20 places available

Here's my code for saving the information from the file as objects.

public class Parties
{
   static Scanner input = new Scanner(System.in);


  public static void main(String[] args) throws FileNotFoundException
  {

     Scanner inFile = new Scanner(new FileReader ("C:\\desktop\\file.txt")); 

     int first = inFile.nextInt();
     inFile.nextLine();


    for(int i=0; i < first ; i++)
    {
        String str = inFile.nextLine();
        String[] e = str.split("\\n");

        String name = e[0];
        int tickets= Integer.parseInt(e[1]); //this is where it throw an error ArrayIndexOutOfBoundsException, i read about it and I still don't understand

        Party newParty = new Party(name, tickets);
        System.out.println(name+ " " + tickets);
    }

This is my SingleParty Class:

public class SingleParty
{
    private String name;
    private int tickets;


    public Party(String newName, int newTickets)
    {
        newName = name;
        newTickets = tickets;

    } 

Can someone explain to me how could I approach this error?

Thank you

str only contains the party name and splitting it won't work, as it won't have '\\n' there.

It should be like this within the loop:

String name = inFile.nextLine();
int tickets = inFile.nextInt();

Party party = new Party(name, tickets);

// Print it here.

inFile().nextLine(); // for flushing

nextLine() returns a single string.

Consider the first iteration, for example, "Christmas Party".

If you split this string by \\n all you're gonna get is "Christmas Party" in an array of length 1. Split by " blank space " and it should work.

You could create a HashMap and put all the options into that during your iteration.

HashMap<String, Integer> hmap = new HashMap<>();

while (sc.hasNext()) {
      String name = sc.nextLine();
      int tickets = Integer.parseInt(sc.nextLine());
      hmap.put(name, tickets);
}

You can now do what you need with each entry in the HashMap .

Note: this assumes you've done something with the first line of the text file, the 4 in your example.

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