Reading file and storing in an array.
this is doing my box in, been at it for days with no luck, and it really should be very straight forward.
Basically i hvae to readin this file and store it in an array.
i have created my player class but i have no idea who to make an array of player from the file.
the file contents are (in the file they are separeted by tabs)
BledsoeDrew2532Eagles
BollerKyle2442Rams
BollingerBrooks4051Rams
BradyTom4311Eagles
BreesDrew1421Eagles
BrooksAaron4153Eagles
BrunellMark3341Eagles
BulgerMarc1420Eagles
CarrDavid2401Eagles
CulpepperDaunte3415Rams
DelhommeJake4343Eagles
DilferTrent2523Rams
FavreBrett3502Eagles
FitzpatrickRyan5520Rams
FrerotteGus3312Eagles
FryeCharlie1242Rams
GarciaJeff4212Rams
GarrardDavid1451Rams
GreenTrent1412Eagles
GrieseBrian2412Rams
HarringtonJoey2310Rams
HasselbeckMatt2245Eagles
HolcombKelly2123Rams
JohnsonBrad2051Rams
LeftwichByron1151Eagles
LosmanJ.P.3341Rams
ManningPeyton1402Eagles
ManningEli1113Eagles
MartinJamie3345Rams
McCownJosh1452Rams
McMahonMike4212Rams
McNabbDonovan2410Eagles
McNairSteve2233Eagles
PalmerCarson1501Eagles
PlummerJake0543Eagles
RattayTim3342Rams
RoethlisbergerBen2422Eagles
RosenfelsSage5220Rams
SchaubMatt4110Rams
SimmsChris3232Rams
SorgiJim3242Rams
VickMichael3255Eagles
WarnerKurt4042Eagles
WrightAnthony4241Rams
my players class is like so...........
publicclass Playerextends Object
{
private String name;
private String surname;
private String prn;
private String arn;
private String drn;
private String grn;
private String team;
privateint Passing;
privateint Attacking;
privateint Defending;
privateint Goalkeeping;
public Player()
{
//empty constructor
}
public Player(String name1, String surname1,int PassingRating,int AttackingRating,int DefendingRating,int GoalkeepingRating, String team1)
{
name=name1;
surname=surname1;
Passing = PassingRating;
Attacking = AttackingRating;
Defending = DefendingRating;
Goalkeeping = GoalkeepingRating;
team=team1;
}
publicvoid setName(String aname)
{
this.name=aname;
}
publicvoid setSurname(String sname)
{
this.surname=sname;
}
publicvoid setPassing(int pr)
{
this.Passing=pr;
}
publicvoid setAttacking(int ar)
{
this.Attacking=ar;
}
publicvoid setDefending(int dr)
{
this.Defending=dr;
}
publicvoid setGoalkeeping(int gr)
{
this.Goalkeeping=gr;
}
publicvoid setTeam(String ateam)
{
this.team=ateam;
}
}
i have been mssing around with the following but with no luck.
publicvoid loadFromFile(String fname)
{
File f =new File("Players1.txt");
Scanner in = this.openFile(f);
int x=0;
while(in.hasNextLine())
{
Player p =new Player(in);
x++;
}
in.close();
this.Players =new Player[x];
File g =new File("Players1.txt");
in =new Scanner(g).useDelimiter("\t");
for (int i = 0; 1 < x; i++)
{ this.Players[i] =new Player(in);
}
in.close();
}
Have search every where but can find no help on this, only how to read single INTs of Strings into arrays.
[6213 byte] By [
UFC1a] at [2007-11-27 2:37:56]

well i wondering wheather you can solve this by using a string tokenizer.
1) Use a List to store the Players in as you read them, since you don't necessarily know how many there are when you start.
2) You have to read a single line from the file, then parse that line to get the individual fields (name, surname, etc) which you then pass to the Player constructor.
3) After you read the whole file, you can get the array of Players from the List of Players.
public void loadFromFile(String fname)
{
File f = new File("Players1.txt");
Scanner in = this.openFile(f);
int x=0;// you don't need this variable
// create your List to store the Players here
while(in.hasNextLine())
{
// parse out the fields. Use String.split()
//Player p = new Player(in);// don't pass the Scanner to the Player constructor
// create a player with those parsed fields
// add the new Player p to the List, if you don't then you're just throwing away the newly constructed Player
x++;
}
in.close();
// you don't need the rest of this
/*this.Players = new Player[x];
File g = new File("Players1.txt");
in = new Scanner(g).useDelimiter("\t");
for (int i = 0; 1 < x; i++)
{ this.Players[i] = new Player(in);
}
in.close();*/
}
?public Class TableParser{
/* Returns an array of Player class instances by taking filename(textfile) as an input in the specified format */
public Player[] getPlayerList(File aFile) {
List<Player> alist = new ArrayList<Player>();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
while (( line = input.readLine()) != null){
String arry[] = this.getStringArray(line);
if(arry.length == 7){
Player player = new Player();
player.setSurname(arry[0]);
player.setName(arry[1]);
player.setPassing(Integer.parseInt(arry[2]));
player.setAttacking(Integer.parseInt(arry[3]));
player.setDefending(Integer.parseInt(arry[4]));
player.setGoalKeeping(Integer.parseInt(arry[5]));
player.setTeam(arry[6]);
alist.add(player);
}
}
}catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex){
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
return alist.toArray(new Player[alist.size()]);
}
/*Divides the string into an array of String as per the supposed rule of sperating each field*/
public String[] getStringArray(String str){
ArrayList<String> alist = new ArrayList<String>();
StringTokenizer strTok = new StringTokenizer(str);
while(strTok.hasMoreElements()))
alist.add(strTok.nextElement());
return alist.toArray(new String[alist.size()]);
}
}
Hope that might help :)
REGARDS,
RaHuL
1st off thanks for all replys,
while i have no doubt you code is fine RaHuL i cant get it to work. My level of java is so bad a this point that might have well been in spanish :-D.
I've been trying the following, its really annonyine me for once i make my array the rest is plane sailing, but we have only been shown how to populate an array of Ints.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.io.PrintWriter;
public class ResultPredictor
{
Player[] plyer = new Player[44];
public static void main (String args[])
{
//display menu to user & process user choice
Scanner input = new Scanner(System.in);
int choice = 0;
while(choice!=8)
{
System.out.println("_");
System.out.println("");
System.out.println("[1] List all avaliable players");
System.out.println("[2] Please enter the name of a player to display his ability scores");
System.out.println("[3] Add a player to the Eagles");
System.out.println("[4] Add a player to the Rams");
System.out.println("[5] Display the players selected to play for the Eagles");
System.out.println("[6] Display the players selected to play for the Rams");
System.out.println("[7] Calculate which team will win the game");
System.out.println("[8] Exit");
System.out.println("");
System.out.print("What is your choice? ");
System.out.flush();
//check and process an integer choice
if (input.hasNextInt())
{
choice=input.nextInt();
switch(choice)
{
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
case 7:
break;
case 8:
break;
default:
System.out.println("Please enter a valid menu option (1-8)");
System.out.println("");
break;
}
}
else //choice was not an integer
{
System.out.println("Please enter a valid menu option (1-8)");
input.next(); //move on
}
}//end loop
}// end main
public static void playerArr()
{
Scanner input = new Scanner(System.in);
try
{
String fn = "";
String sn = "";
int a = 0;
int b = 0;
int c = 0;
int d = 0;
String tm = "";
int x=0;
File f = new File("airports.txt");
Scanner in = new Scanner(f).useDelimiter("\t");
while(in.hasNextLine())
{
sn = in.next();
fn = in.next();
a = in.nextInt();
b = in.nextInt();
c = in.nextInt();
d = in.nextInt();
tm =in.nextLine();
plyer [x] = new plyer(fn, sn, a, b, c, d, tm);
x++;
}
in.close();
}
catch(FileNotFoundException e)
{
System.out.println("WARNING . . the data file cannot be found");
}
}
}
UFC1a at 2007-7-12 2:58:37 >

Did you see my reply in your other post, UFC1? Really, you should build on that one instead of complicating things by posting two seperate topics for the same basic thing - it's makes it easier for us to focus on the progress you are making.
yeah sorry, problem is the way i've made my first array makes it hard for me to make the rest of the prog. thanks for the help.
UFC1a at 2007-7-12 2:58:37 >

Ah, I see. And I apologize too - I had not seen your reply to my last post in your other topic.
But one thing confuses me - you just said above:
"once i make my array the rest is plane sailing, but we have only been shown how to populate an array of Ints."
What exactly do you mean, because you were making an array of Strings in your other topic?
yeah, now i've realised if i can make an array of the class then i can complete the rest of the programme with a fe simple methods. By making an array of the string i will have to convert alot of it back to INTs.
UFC1a at 2007-7-12 2:58:37 >

Follow the methodology that RahulSharna demonstrated - that's the way to do it.
Here's another slightly different way to do it - more similar to what you already had:
Place the following in Playeri.java:
public class Player1
{
private String name;
private String surname;
private String prn;
private String arn;
private String drn;
private String grn;
private String team;
private int Passing;
private int Attacking;
private int Defending;
private int Goalkeeping;
public Player1()
{
//empty constructor
}
public Player1(String name1,
String surname1,
intPassingRating,
intAttackingRating,
intDefendingRating,
intGoalkeepingRating,
String team1)
{
name= name1;
surname= surname1;
Passing= PassingRating;
Attacking= AttackingRating;
Defending= DefendingRating;
Goalkeeping = GoalkeepingRating;
team= team1;
}
public void setName(String aname)
{
this.name=aname;
}
public void setSurname(String sname)
{
this.surname=sname;
}
public void setPassing(int pr)
{
this.Passing=pr;
}
public void setAttacking(int ar)
{
this.Attacking=ar;
}
public void setDefending(int dr)
{
this.Defending=dr;
}
public void setGoalkeeping(int gr)
{
this.Goalkeeping=gr;
}
public void setTeam(String ateam)
{
this.team=ateam;
}
Place the following in Players.java:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Players
{
// private PrintWriter output;
public Players()
{
}
public static void main(String[] argv)
{
if ( argv.length != 1 )
{
System.out.println("Usage: java Players <filename>");
system.exit(-1);
}
Players avbplayers = new Players();
System.out.println("Reading Player data");
List[] playerTypes = avbplayers.loadFromFile(argv[0]);
if (playerTypes.length == 2)
{
Player1[] plyers= ( ( (Player1[])playerTypes[0] ).toArray() );
Player1[] starsPlyers = ( ( (Player1[])playerTypes[1] ).toArray() );
}
System.out.println("Players loaded");
viewPlayers(plyers);
viewPlayers(startsPlyers);
}
public void viewPlayers(Player1[] players)
{
for ( Player1 player : players )
System.out.println(players);
}
public List[] loadFromFile(String fname)
{
String name = "";
String surname= "";
String team = "";
intPassing= 0;
intAttacking= 0;
intDefending= 0;
intGoalkeeping = 0;
Scanner in= null;
Listplyer= new ArrayList();
ListstarsPlyer= new ArrayList();
File infile = new File(fname);
if ( infile.exists() && !infile.isDirectory() ) {
try {
in = new Scanner(infile).useDelimiter("\t");
int x=0;
while(in.hasNextLine()) {
surname= in.next();
name= in.next();
Passing= in.nextInt();
Attacking= in.nextInt();
Defending= in.nextInt();
Goalkeeping = in.nextInt();
team=in.nextLine();
plyer.add(new Player1(name, surname, Passing, Attacking, Defending, Goalkeeping, team));
String presult = "";
if (this.Passing == 1)
{
presult = "*";
}
if (this.Passing == 2)
{
presult = "**";
}
if (this.Passing == 3)
{
presult = "***";
}
if (this.Passing == 4)
{
presult = "****";
}
if (this.Passing == 5)
{
presult = "*****";
}
String aresult = "";
if (this.Attacking == 1)
{
aresult = "*";
}
if (this.Attacking == 2)
{
aresult = "**";
}
if (this.Attacking == 3)
{
aresult = "***";
}
if (this.Attacking == 4)
{
aresult = "****";
}
if (this.Attacking == 5)
{
aresult = "*****";
}
String dresult = "";
if (this.Defending == 1)
{
dresult = "*";
}
if (this.Defending == 2)
{
dresult = "**";
}
if (this.Defending == 3)
{
dresult = "***";
}
if (this.Defending == 4)
{
dresult = "****";
}
if (this.Defending == 5)
{
dresult = "*****";
}
String gresult = "";
if (this.Goalkeeping == 1)
{
gresult = "*";
}
if (this.Goalkeeping == 2)
{
gresult = "**";
}
if (this.Goalkeeping == 3)
{
gresult = "***";
}
if (this.Goalkeeping == 4)
{
gresult = "****";
}
if (this.Goalkeeping == 5)
{
gresult = "*****";
}
starsPlyer.add(new Player1(name, surname, Passing, Attacking, Defending, Goalkeeping, team));
}
if (in != null)in.close();
if (output != null) output.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Error: File not Found!!\n"+fnfe);
} catch (IOException ioe) {
System.out.println("Error: Other IOException!!\n"+ioe);
} catch (Exception e) {
System.out.println("Error\n"+e);
}
return( new List[] = {plyer, starsPlyer};
}
}
Please note that I did not compile this here because, being on v1.4.x, I don't have Scanner
Has anyone suggested rewriting this stuff with loops?
String gresult = "";
if (this.Goalkeeping == 1)
{
gresult = "*";
}
if (this.Goalkeeping == 2)
{
gresult = "**";
}
if (this.Goalkeeping == 3)
{
gresult = "***";
}
if (this.Goalkeeping == 4)
{
gresult = "****";
}
if (this.Goalkeeping == 5)
{
gresult = "*****";
}
String gresult = "";
for (int i=0; i<this.Goalkeeping; i++) {
gresult += "*";
}
>
!!YIPES!!! ... I replaced the Scanner with a BufferedReader and compiled my code - yuck , just full of errors. I fixed them though and here is working code (assuming however, that the file is space delimited and looks like this:)
File
name1 George 6 3 9 2 team1
name2 Burt 9 2 7 4 team2
name3 Valerie 12 12 0 3 team3
name4 Kim 0 4 10 8 team4
Code for Player1
public class Player1
{
private String name;
private String surname;
private String prn;
private String arn;
private String drn;
private String grn;
private String team;
private int Passing;
private int Attacking;
private int Defending;
private int Goalkeeping;
public Player1()
{
}
public Player1(String name1,
String surname1,
intPassingRating,
intAttackingRating,
intDefendingRating,
intGoalkeepingRating,
String team1)
{
name= name1;
surname= surname1;
Passing= PassingRating;
Attacking= AttackingRating;
Defending= DefendingRating;
Goalkeeping = GoalkeepingRating;
team= team1;
}
public void setName(String aname)
{
this.name=aname;
}
public void setSurname(String sname)
{
this.surname=sname;
}
public void setPassing(int pr)
{
this.Passing=pr;
}
public void setAttacking(int ar)
{
this.Attacking=ar;
}
public void setDefending(int dr)
{
this.Defending=dr;
}
public void setGoalkeeping(int gr)
{
this.Goalkeeping=gr;
}
public void setTeam(String ateam)
{
this.team=ateam;
}
public String toString()
{
return(name+"\t"+surname+"\t"+Passing+"\t"+Attacking+"\t"+Defending+"\t"+Goalkeeping+"\t"+team);
}
}
Code for Players
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.*;
import java.util.*;
public class Players
{
public Players()
{
}
public static void main(String[] argv)
{
Player1[] plyers= null;
Player1[] starsPlyers = null;
if ( argv.length != 1 )
{
System.out.println("Usage: java Players <filename>");
System.exit(-1);
}
Players avbplayers = new Players();
System.out.println("Reading Player data");
List[] playerTypes = avbplayers.loadFromFile(argv[0]);
if (playerTypes.length == 2)
{
if (playerTypes[0] != null && playerTypes[0] instanceof ArrayList)
{
Object[] o1 = playerTypes[0].toArray();
plyers= new Player1[o1.length];
for (int i = 0; i < plyers.length; i++)
plyers[i] = (Player1)o1[i];
}
if (playerTypes[1] != null && playerTypes[1] instanceof ArrayList)
{
Object[] o2 = playerTypes[0].toArray();
starsPlyers = new Player1[o2.length];
for (int i = 0; i < starsPlyers.length; i++)
starsPlyers[i] = (Player1)o2[i];
}
}
System.out.println("Players loaded");
avbplayers.viewPlayers(plyers);
avbplayers.viewPlayers(starsPlyers);
}
public void viewPlayers(Player1[] players)
{
for ( int i = 0; i < players.length; i++ )
System.out.println(players[i]);
}
public List[] loadFromFile(String fname)
{
String record= "";
String[]elements;
String name = "";
String surname= "";
String team = "";
intPassing= 0;
intAttacking= 0;
intDefending= 0;
intGoalkeeping = 0;
Listplyer= new ArrayList();
ListstarsPlyer= new ArrayList();
BufferedReader in= null;
File infile = new File(fname);
if ( infile.exists() && !infile.isDirectory() )
{
try
{
in = new BufferedReader(new FileReader(infile));
int x=0;
while( (record = in.readLine()) != null)
{
elements = record.split(" ");
surname= elements[0];
name= elements[1];
Passing= Integer.parseInt(elements[2]);
Attacking= Integer.parseInt(elements[3]);
Defending= Integer.parseInt(elements[4]);
Goalkeeping = Integer.parseInt(elements[5]);
team= elements[6];
plyer.add(new Player1(name, surname, Passing, Attacking, Defending, Goalkeeping, team));
starsPlyer.add(new Player1(name, surname, Passing, Attacking, Defending, Goalkeeping, team));
}
if (in != null)in.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Error: File not Found!!\n"+fnfe);
} catch (IOException ioe) {
System.out.println("Error: Other IOException!!\n"+ioe);
} catch (Exception e) {
System.out.println("Error\n"+e);
}
}
return( new List[] {plyer, starsPlyer} );
}
}
HTH
Thanks for all your help, ha the only prob being ght e file is tab delimited. No biggy though i'm sure i'll work out how to get around it. Again many thanks.
UFC1a at 2007-7-12 2:58:37 >
