Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Trying to read objects from file into ArrayList

  1. #1
    Junior Member
    Join Date
    Jun 2019
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Trying to read objects from file into ArrayList

    I am working on my own personal project where you keep a record of Player objects in a file. I have created a way create a new file and add Player objects to it, or open an existing file and add Player objects. However, to delete a Player object from an existing file, I have to read the Player objects from that file into an ArrayList. Then delete the desired Object, preferably using the remove() method. Once that is done, I write the ArrayList into the file again. This time without the Objects that I removed.

    However, I keep getting this error:

    HTML Code:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    	at roster.Team.delete(Team.java:98)
    	at roster.Driver.main(Driver.java:26)
    I can't get my code to work without solving this error. It would be much appreciated if someone could help me.

    Run my code below to see the issue:

    HTML Code:
    package roster;
    
    import java.io.IOException;
    
    import java.util.Scanner;
    
    public class Driver {
    
    	public static void main(String[] args) throws IOException {
    
    		Team t1 = new Team();
    		System.out.println("To create a new roster, type 1");
    		System.out.println("To add to an existing roster, type 2");
    		System.out.println("To remove a player from a roster, type 3");
    		
    		Scanner scan = new Scanner(System.in);
    		int choice = scan.nextInt();
    		
    		if(choice == 1){
    			t1.input();
    		}
    		if(choice == 2){
    			t1.add();
    		}
    		if(choice == 3){
    			t1.delete();
    		}
    		scan.close();
    
    	}
    
    }
    HTML Code:
    package roster;
    
    import java.io.BufferedWriter;
    
    import java.io.FileWriter;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.stream.Stream;
    import java.io.ObjectInputStream;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.io.FileInputStream;
    
    import java.io.*;
    
    public class Team {
    
    	ArrayList<Player> x = new ArrayList<Player>();
    
    	public Team(){
    		this.x = new ArrayList<>();
    	}
    	Scanner scan = new Scanner(System.in);
    	public void input() throws IOException {
    		int num_people;
    		System.out.print("Name of file (A file that does not exist will be automatically created): ");
    		String name;
    		name = scan.next();
    		System.out.print("# of people on roster? ");
    		num_people = scan.nextInt();
    		System.out.println("Enter first, last, goals, caps, and assists:");
    		for(int i=0; i<num_people; i++){
    			String fstname2 = scan.next();
    			String lstname2 = scan.next();
    			String goals = scan.next();
    			String caps = scan.next();
    			String assists = scan.next();
    			x.add(new Player(fstname2,lstname2,goals,caps,assists));
    		}
    		scan.close();
    		System.out.println("Done.");
    		
    		BufferedWriter writer = new BufferedWriter(new FileWriter(name));
    	    for(Player p : x)
    	        if(p != null){
    	            writer.write(p + "\n");
    	            writer.newLine();
    	        }
    	    writer.close();
    	}
    	public void add() throws IOException {
    		System.out.println("Enter the name of the file that you wish to add information to: ");
    		String name = scan.next();
    		File w = new File(name);
    		if(w.exists())
    		{
    		    System.out.println("How many people would you like to add? ");
    			int num_people = scan.nextInt();
    			System.out.println("Enter first, last, goals, caps, and assists:");
    			for(int i=0; i<num_people; i++){
    				String fstname2 = scan.next();
    				String lstname2 = scan.next();
    				String goals = scan.next();
    				String caps = scan.next();
    				String assists = scan.next();
    				x.add(new Player(fstname2,lstname2,goals,caps,assists));
    			}
    			System.out.println("Done.");
    			
    			BufferedWriter q = new BufferedWriter(new FileWriter(w, true));
    		    for(Player p : x){
    		    	q.write(p + "\n");
    		    	q.newLine();
    		    }
    		    q.close();
    		}
    		else{
    			System.out.println("File does not exist.");
    		}
    	}
    	public void delete() throws IOException {
    		System.out.println("Enter the name of the file that you wish to delete information from: ");
    		String name = scan.next();
    		File w = new File(name);
    		if(w.exists())
    		{
    	        try {
    	            Scanner sc = new Scanner(w);
    
    	            ArrayList<Player> x = new ArrayList<Player>();
    
    	            while(sc.hasNextLine()){
    	                String line = sc.nextLine();
    	                String[] details = new String[4];
    	                details = line.split(" ");
    	                String fstname = details[0];
    	                String lstname = details[1];
    	                String goals = details[2];
    	                String caps = details[3];
    	                String assists = details[4];
    	                //int age = Integer.parseInt(details[2]);
    	                Player p = new Player(fstname,lstname,goals,caps,assists);
    	                x.add(p);
    	            }
    
    	            for(Player p: x){
    	                System.out.println(p.toString());
    	            }
    
    	        } catch (FileNotFoundException e) {         
    	            e.printStackTrace();
    	        }
    
    		    System.out.println("How many people would you like to remove? ");
    			int num_people = scan.nextInt();
    			System.out.println("Enter first, last, goals, caps, and assists:");
    			for(int i=0; i<num_people; i++){
    				String fstname2 = scan.next();
    				String lstname2 = scan.next();
    				String goals = scan.next();
    				String caps = scan.next();
    				String assists = scan.next();
    				x.remove(new Player(fstname2,lstname2,goals,caps,assists));
    			}
    			System.out.println("Done.");
    			System.out.println();
    			for(int i=0;i<x.size();i++){
    		    	System.out.println(x.get(i));
    		    }
    			BufferedWriter q = new BufferedWriter(new FileWriter(w));  //The Object I "deleted" still shows up in file
    		    for(Player p : x){
    		    	q.write(p + "\n");
    		    	q.newLine();
    		    }
    		    q.close();
    		}
    		else{
    			System.out.println("File does not exist.");
            }
    	}
    HTML Code:
    package roster;
    
    public class Player {
    
    	String fstname, lstname, goals, caps, assists;
    	
    	public Player(String fstname, String lstname, String goals_, String caps_, String assists_) {
    		super();
    		this.fstname = fstname;
    		this.lstname = lstname;
    		this.goals = goals_;
    		this.caps = caps_;
    		this.assists = assists_;
    	}
    	public String toString(){
    		return fstname + " " + lstname + " " + goals + " " + caps + " " + assists;
    	}
    	public String getFstname() {
    		return fstname;
    	}
    	public void setFstname(String fstname) {
    		this.fstname = fstname;
    	}
    	public String getLstname() {
    		return lstname;
    	}
    	public void setLstname(String lstname) {
    		this.lstname = lstname;
    	}
    	public String getGoals() {
    		return goals;
    	}
    	public void setGoals(String goals) {
    		this.goals = goals;
    	}
    	public String getCaps() {
    		return caps;
    	}
    	public void setCaps(String caps) {
    		this.caps = caps;
    	}
    	public String getAssists() {
    		return assists;
    	}
    	public void setAssists(String assists) {
    		this.assists = assists;
    	}
    }

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to read objects from file into ArrayList

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
    at roster.Team.delete(Team.java:98)
    At line 98 the code tries to access an array with an index past the end of the array. The array needs to have at least two elements to be able to index it with an index of 1.
    What is the size of the array being indexed at line 98? If you expect at least 2 elements in the array where are they?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jun 2019
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Trying to read objects from file into ArrayList

    If you look at line 95, I made the size of the array to hold 5 elements.

    String[] details = new String[4];

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to read objects from file into ArrayList

    I made the size of the array to hold 5 elements.
    No, the code says 4 elements.
      String[] details = new String[4];  //  Define array to hold 4 Strings
      details = line.split(" ");               //  Create new array with the split method
    The split method returns an array that replaces what was defined before.
    Check that the size of the array is >= 5 before trying to index the first 5 slots in the array

    Use the Arrays class's toString method to see the contents of the array:
      System.out.println("details="+ java.util.Arrays.toString(details));
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jun 2019
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Trying to read objects from file into ArrayList

    I fixed the code to say 4 elements instead of 5.

    This line only returns the first object I have in the file:

    HTML Code:
    System.out.println("details="+ java.util.Arrays.toString(details));
    Does this mean that the details array only holds one line?

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to read objects from file into ArrayList

    Does this mean that the details array only holds one line?
    Add that statement after the split method call to see what was in the array that was created.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Jun 2019
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Trying to read objects from file into ArrayList

    I did

    This is my output:

    details=[Simon, Markus, 0, 0, 0]
    details=[]

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to read objects from file into ArrayList

    Ok, that says the first time the array has the 5 elements shown in the print out. Are those the expected values?
    The second time it says that there are no elements in the array. What is in the second line of the file?

    What is the value of line when the split method is called? Add a print statement to print it out.
    If you don't understand my answer, don't ignore it, ask a question.

  9. #9
    Junior Member
    Join Date
    Jun 2019
    Posts
    27
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Trying to read objects from file into ArrayList

    That's the problem, it does not read the next two lines. It only reads the first line, and I want to get it to read ALL of the lines in the file. And put all of those objects into an ArrayList, so that I can then delete one from the keyboard.

  10. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Trying to read objects from file into ArrayList

    it does not read the next two lines.
    The print out shows that it reads two lines. When it gets the exception that throws it out of the loop.
    If it didn't get the exception, it should continue reading lines as long as sc.hasNextLine() returns true.
    Add code to skip accessing the elements of an array that is empty to prevent the exception.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Read .txt file and create objects using data
    By sevans20 in forum File I/O & Other I/O Streams
    Replies: 1
    Last Post: April 14th, 2012, 01:52 PM
  2. Read input, read file, find match, and output... URGENT HELP!
    By MooseHead in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2012, 11:01 AM
  3. Really need some help with Objects inside an ArrayList
    By ISuckSoBad in forum What's Wrong With My Code?
    Replies: 1
    Last Post: May 15th, 2011, 12:33 PM
  4. Arraylist Objects to Database
    By frankycool in forum JDBC & Databases
    Replies: 3
    Last Post: November 15th, 2009, 08:01 PM
  5. Object creation from a input file and storing in an Array list
    By LabX in forum File I/O & Other I/O Streams
    Replies: 4
    Last Post: May 14th, 2009, 03:52 AM

Tags for this Thread