Reputation: 11
I have three *.csv files and I'm using an interface to compare the objects.
My question is: how to add only certain data to an array list?
For example, I only need items[1]
which is yearID
, items[2]
which is teamID
, items[11]
which is homeRuns
, and items [12]
which is RBI
value.
How to add them into an arrayList
while still making them a value in the Batter
class, and then passing the array list to another class? Here is the first two lines of the file
playerID yearID stint teamID lgID G AB R H 2B 3B HR RBI SB CS BB SO IBB HBP SH SF GIDP abercda01 1871 1 TRO NA 1 4 0 0 0 0 0 0 0 0 0 0
Batter.java `
import java.util.ArrayList;
import java.util.Scanner;
public class Batter extends Player{
private int YearID;
private String TeamID;
private int HomeRuns;
private int RBI;
public Batter(int yearID, String teamID, int homeRuns, int rBI) {
super();
YearID = yearID;
TeamID = teamID;
HomeRuns = homeRuns;
RBI = rBI;
}
Batter() throws Exception{
ArrayList<String> battingData= new ArrayList<String>();
ArrayList<String> masterData= new ArrayList<String>();
ArrayList<String> pitchingData= new ArrayList<String>();
Scanner myScan1= new Scanner(new File("Batting.cvs"));
while(myScan1.hasNext()) {
while(myScan1.hasNext()) {
battingData.add(myScan1.nextLine());
String line= myScan1.nextLine();
String items[]= line.split(",")
for( int i= 0; i<battingData.size(); i++){
battingData.add(new Players(Integer.parseInt(items[0]));
}
}
}
Players.java
import java.util.ArrayList;
import java.util.Arrays;
public class Players {
private ArrayList Player[];
public Players (String BatData, String PitData,String MasterData) {
}
}
Upvotes: 1
Views: 334
Reputation: 794
A few important points. You were looping myScan1.hasNext() twice unnecessarily. You were also discarding one line as you were calling nextLine twice. I have proposed below a suggestion of how you can achieve what you want.
while (myScan1.hasNext()) {
String line = myScan1.nextLine();
battingData.add(line);
String items[]= line.split(",")
for( int i= 0; i<battingData.size(); i++){
String yearID = items[1];
String teamID = items[2];
String homeRuns = items[11];
String rbi = items[12];
// do what you need to do with these variables
}
}
Upvotes: 1