Adding to an object array list using a file reader - java

Basically I have to classes interacting with one another in this situation one company and one the driver, this code is written in the driver. So I am using a file reader to scan a text file that looks like this with a space between each line.
John:Smith:Manufacturing:6.75:120:444
Betty:White:Manager:1200.00:111
Stan:Slimy:Sales:10000.00:332
Betty:Boop:Design:12.50:50:244
And the code is as follows. The addEmployee method of the company class has a (string, string, string, double, int, int) parameter. The text file it reads in has a colons inbetween each part, so howe can I add it to the arraylist of objects. And keep going until all of them are read. Sorry if my questions difficult to understand, if you want me to elaborate let me know in the comments. I just didn't want to make the question too long.
else if (e.getSource()==readButton){
JFileChooser fileChooser = new JFileChooser("src");
if (fileChooser.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
{
empFile=fileChooser.getSelectedFile();
}
Scanner scan = new Scanner("empFile");
while(scan.hasNext()){
scan.next().split(":");
if (position.equals("Manager")){
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
}
else if(position.equals("Sales")){
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), 0, Integer.parseInt(empNum2));
}
else{
c.addEmployee(fName, lName, position2, Double.parseDouble(firstParam2), Integer.parseInt(secondParam2), Integer.parseInt(empNum2));
}
}

This line:
scan.next().split(":");
Will return an array of Strings that you're not storing anywhere. Turn it into:
String[] rowData = scan.next().split(":");
And use every item in the array as you wish, for example to fill your variables or directly as arguments for your class constructor. Providing a sample of the former:
fName = rowData[0];
lName = rowData[1];
position = rowData[2];
firstParam2 = rowData[3];
secondParam2 = rowData[4];
empNum2 = rowData[5];

Related

How to delimit new line when reading CSV file?

I am trying to read a file where each line has data members, separated by commas, that are meant to populate an object's data members, I tried using the regex "|" symbol to separate "," and "\n" along with "\r" for getting to the new line. However, after reading the first line, the first data member of the second line does not get read right away but rather a "" character gets read beforehand. Am I using the wrong regex symbols? or am I not using the right approach? I read that there are many ways to tackle this and opted to use scanner since seemed the most simple, using the buffer reader seemed very confusing since it seems like it returns arrays and not individual strings and ints which is I'm trying to get.
The CSV file looks something like this
stringA,stringB,stringC,1,2,3
stringD,stringE,stringF,4,5,6
stringG,stringH,stringI,7,8,9
My code looks something like this
//In list class
public void load() throws FileNotFoundException
{
Scanner input = new Scanner(new FileReader("a_file.csv"));
object to_add; //To be added to the list
input.useDelimiter(",|\\n|\\r");
while (input.hasNext())
{
String n = input.next(); //After the first loop run, this data gets the value ""
String l = input.next(); //During this second run, this member gets the data that n was supposed to get, "stringD"
String d = input.next(); //This one gets "stringE"
int a = input.nextInt(); //And this one tries to get "stringF", which makes it crash
int c = input.nextInt();
to_add = new object(n, l, d, a, b, c); //Calling copy constructor to populate data members
insert(to_add); //Inserting object to the list
}
input.close();
}
Use Apache Commons CSV. Here is the user guide https://commons.apache.org/proper/commons-csv/user-guide.html
You can do this with OpenCSV and here is a tutorial how to use this library. You can download the library from the Maven Repository.
So following is the code what you need to do,
Reader reader = Files.newBufferedReader(Paths.get("path/to/csvfile.csv"));
CSVReader csvReader = new CSVReader(reader);
List<String[]> dataList = new ArrayList<>();
dataList = csvReader.readAll();
reader.close();
csvReader.close();
Object to_add;
for (String[] rowData : dataList) {
String textOne = rowData[0];
String textTwo = rowData[1];
String textThree = rowData[2];
int numberOne = Integer.parseInt(rowData[3]);
int numberTwo = Integer.parseInt(rowData[4]);
int numberThree = Integer.parseInt(rowData[5]);
to_add = new Object(textOne, textTwo, textThree, numberOne, numberTwo, numberThree);
insert(to_add);
}

Storing data from jfilechooser

So I'm writing a car loan amortization GUI program. The end goal is to get either user input data or input from a file and display the payment schedule. I have the user input schedule displaying to the console window for now but my main question is how do I store the data from the text file into variables in order to plug them into the equation?
I am using scanner and stringbuilder and am able to display the contents of the file in the console window, but can't figure out how to store the values into variables. Also if anyone has any tips as to how to display the schedule from the console window onto a second GUI, that would be nice as well.
File workingDir = new File(System.getProperty("user.dir"));
JFileChooser openfile = new JFileChooser();
openfile.setDialogTitle("Choose a file");
openfile.setCurrentDirectory(workingDir);
int status = openfile.showOpenDialog(null);
try {
if(status != JFileChooser.APPROVE_OPTION)
{
return null; // error
}
else {
File file = openfile.getSelectedFile();
Scanner scan = new Scanner(file);
StringBuilder info = new StringBuilder();
while (scan.hasNext()) {
String data = scan.nextLine();
System.out.println(data);
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
}
return null;
}`
Your obviously not showing the actual method declaration for your sample code and by the look of it your data file only contains a single line so I'm just going to wing it here.
Everything within a text file is considered as String content. To convert the data within a text file you would need to use parsers. Your comma delimited file data line contains 3 specific values which would definitely benefit (for now) being of double data type. In order to segment this data line and place the value contents into double type variables you would need to use the String.split() method:
In my opinion I think it's just better to read each file line in its entirety by using hasNextLine() in conjunction with scan.NextLine() rather than hasNext():
while (scan.hasNextLine()) {
String data = scan.nextLine();
// Skip blank lines or possible comment lines
// (lines that start with a semi-colon).
if (data.trim().equals("") || data.trim().startsWith(";")) {
continue;
}
// Create an Array of string values.
String[] stringValues = data.split(", ");
}
This now creates a String Array with each element of that array containing the individual values that were contained on the file data line:
stringValues[0] will hold the string: 6500
stringValues[1] will hold the string: 4.5
stringValues[2] will hold the string: 6
Remember, Array indexing starts from 0 not 1. Now all that is needed is to convert and place these elements into individual double data type variables and we can do that like this.
double totalAmount = Double.parseDouble(stringValues[0]);
double interestAmount = Double.parseDouble(stringValues[1]);
double durationAmount = Double.parseDouble(stringValues[2]);
Your while loop could now possibly look like this:
double totalAmount = 0.0;
double interestAmount = 0.0;
double durationAmount = 0.0;
while (scan.hasNextLine()) {
String data = scan.nextLine();
// Skip blank lines or possible comment lines
// (lines that start with a semi-colon).
if (data.trim().equals("") || data.trim().startsWith(";")) {
continue;
}
// Create an Array of string values.
String[] stringValues = data.split(", ");
// Convert String Array elements to their
// respective double type variables.
totalAmount = Double.parseDouble(stringValues[0]);
interestAmount = Double.parseDouble(stringValues[1]);
durationAmount = Double.parseDouble(stringValues[2]);
}
// rest of code here.....
Now it's a matter of you using those double type variables as you see fit to carry out your calculations.
As for displaying a schedule within a GUI I would recommend the use of a JTable. Create your GUI and add a JTable. For now just have all cells accept String rather than specific data types. To add rows of data to your JTable you can use a method like this:
private void addRowToJTable(JTable table, Object[] rowData) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(rowData);
}
The Object Array you pass to this method would contain elements that represent each column of the table. A simple use case would be:
// Table Columns: Payment #, Pymt Date, Payment, Interest, Principle, Balance
Object[] rowData = {"1", "Jun 12, 2018", "$112.39", "$40.63", "$71.76", "$6,428.24"};
addRowToJTable(jTable1, rowData);
Of course you would have this code in a loop of some sort as you build your schedule. If you would like a runnable example application I quickly whipped up to demonstrate this stuff then send me an e-mail. Your example data line could produce a schedule that could look something like this:

Reading data from a file to an object?

Ok another question about my program that I'm writing called "Flight." In my tester I am creating an object from the Flight class called myFlight. The object has several fields (flight name, miles traveled, etc) but what I'm doing is reading the data from a file called input.txt and trying to put it into the object that I created. There are five lines of information on the file that I'm reading. For some reason I can't quite get it right, if anyone could help me fix this problem I would greatly appreciate it.
Here is the Constructor that has all the fields from my Flight class:
public Flight(String name, int num, int miles, String origin, String destination)
{
Airlinename = name;
flightnumber = num;
numofmiles = miles;
Origincity = origin;
Destinationcity = destination;
}
And the part of my program where I created the object and try to read the data from the file. I had created a blank constructor in my class too because I wasn't sure if I was supposed to put anything in the object when I created it.
Flight myFlight = new Flight();
File myFile = new File("input.txt");
Scanner inputFile = new Scanner(myFile);
while (inputFile.hasNext())
{
myFlight = inputFile.nextLine();
}
inputFile.close();
}
}
Just in case you use special characters, you need to modify your program so you can read them correctly.
Scanner inputFile = new Scanner(myFile, "UTF-8");
On the other hand, if the text file contains the following, possibly subsequent calls to nextInt() generate a runtime exception.
Gran EspaƱa
1
1001
New York
Los Angeles
If that were the case, the reading should be different.
myFlight = new Flight(inputFile.nextLine(),
Integer.parseInt(inputFile.nextLine()),
Integer.parseInt(inputFile.nextLine()),
inputFile.nextLine(),
inputFile.nextLine());
As with any program, when adding more conditions to improve the model, it needs more and more code.
Good luck.
try
myFlight = new Flight(inputFile.next(), inputFile.nextInt(),
inputFile.nextInt(), inputFile.next(), inputFile.next());
You can't directly assign a string line to an object, you need to parse the line into parts and assign values to variables one by one.
How is your input text organized? The Scanner's nextLine() method is returning a String object and definitely you cannot assign that to a type Flight. There are different methods to get the different values in the Scanner like nextInt(), nextFloat().
Basically you can try like this
Flight myFlight = new Flight();
myFlight.setFlightName(inputFile.next());
myflight.setMiles(inputFile.nextInt();
etc.
This is just a sample, you need to check the format you have in the input.txt file.

Displaying Stats with arrays in Java

I am trying to display statistics from a simple text file using arrays in Java. I know what I am supposed to do, but I don't really how how to code it. So can anybody show me a sample code on how to do it.
So let's say the text file is called gameranking.txt, that contains the following information (This is a simple txt file to use as an example):
Game Event, 1st place, second place, third place, fourth place
World of Warcraft, John, Michael, Bill, Chris
Call of Duty, Michael, Chris, John, Bill
League of Legends, John, Chris, Bill, Michael.
My goal is to display stats such as how many first places, second places.. each individual won in a table like the following
Placement First place, second, third, fourth
John 2 0 1 0
Chris 0 2 0 1
etc...
My thought:
First, I would read the gameranking.txt and stores it to "input". Then I can use the while loop to read each line and store each line into a string called "line", afterward, I would use the array method "split" to pull out each string and store them into individual array. Afterward, I would count which placement each individual won and display them into a neat table using printf.
My first problem is I don't know how to create the arrays for this data. Do I first need to read through the file and see how many strings are in each row and column, then create the array table accordingly? Or can I store each string in an array as I read them?
The pseudocode that I have right now is the following.
Count how many rows are there and store it in row
Count how many column are there and store it in column
Create an array
String [] [] gameranking = new String [row] [column]
Next read the text file and store the info into the arrays
using:
while (input.hasNextLine) {
String line = input.nextLine();
while (line.hasNext()) {
Use line.split to pull out each string
first string = event and store it into the array
second string = first place
third string =......
Somewhere in the code, I need to count the placement....
Can somebody please show me how I should go about doing this?
I am not going to write the full program, but I will try to tackle each question and give you a simple suggestion:
Reading the initial file, you can get each line and store it in a string using a BufferedReader (or if you like, use a LineNumberReader)
BufferedReader br = new BufferedReader(new FileReader(file));
String strLine;
while ((strLine = br.readLine()) != null) {
......Do stuff....
}
At that point, in the while loop you will go through the string (since it comma delimited, you can use that to seperate each section). for each substring you can
a) compare it with first, second, third, fourth to get placement.
b) if its not any of those, then it could either be a game name or a user name
You can figure that out by position or nth substring (ie if this is the 5th substring, its likely to be the first game name. since you have 4 players, the next game name will be the 10th substring, etc.). Do note, I ignored "Game event" as that's not part of the pattern. You can use split to do this or a number of other options, rather than try to explain that I will give you a link to a tutorial I found:
http://pages.cs.wisc.edu/~hasti/cs302/examples/Parsing/parseString.html
As for tabulating results, Basically you can get an int array for each player which keeps track of their 1st, 2nd, 3rd, awards etc.
int[] Bob = new int[4]; //where 0 denotes # of 1st awards, etc.
int[] Jane = new int[4]; //where 0 denotes # of 1st awards, etc.
Showing the table is a matter of organizing the data and using a JTable in a GUI:
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
Alrighty...Here is what I wrote up, I am sure there is a cleaner and faster way, but this should give you an idea:
String[] Contestants = {"Bob","Bill","Chris","John","Michael"};
int[][] contPlace=new int[Contestants.length][4];
String file = "test.txt";
public FileParsing() throws Exception {
Arrays.fill(contPlace[0], 0);
Arrays.fill(contPlace[1], 0);
Arrays.fill(contPlace[2], 0);
Arrays.fill(contPlace[3], 0);
BufferedReader br = new BufferedReader(new FileReader(file));
String strLine;
while((strLine=br.readLine())!=null){
String[] line = strLine.split(",");
System.out.println(line[0]+"/"+line[1]+"/"+line[2]+"/"+line[3]+"/"+line[4]);
if(line[0].equals("Game Event")){
//line[1]==1st place;
//line[2]==2nd place;
//line[3]==3rd place;
}else{//we know we are on a game line, so we can just pick the names
for(int i=0;i<line.length;i++){
for(int j=0;j<Contestants.length;j++){
if(line[i].trim().equals(Contestants[j])){
System.out.println("j="+j+"i="+i+Contestants[j]);
contPlace[j][i-1]++; //i-1 because 1st substring is the game name
}
}
}
}
}
//Now how to get contestants out of the 2d array
System.out.println("Placement First Second Third Fourth");
System.out.println(Contestants[0]+" "+contPlace[0][0]+" "+contPlace[0][1]+" "+contPlace[0][2]+" "+contPlace[0][3]);
System.out.println(Contestants[1]+" "+contPlace[1][0]+" "+contPlace[1][1]+" "+contPlace[1][2]+" "+contPlace[1][3]);
System.out.println(Contestants[2]+" "+contPlace[2][0]+" "+contPlace[2][1]+" "+contPlace[2][2]+" "+contPlace[2][3]);
System.out.println(Contestants[3]+" "+contPlace[3][0]+" "+contPlace[3][1]+" "+contPlace[3][2]+" "+contPlace[3][3]);
System.out.println(Contestants[4]+" "+contPlace[4][0]+" "+contPlace[4][1]+" "+contPlace[4][2]+" "+contPlace[4][3]);
}
If you need to populate the contestants array or keep track of the games, you will have to insert appropriate code. Also note, using this 2-d array method is probably not best if you want to do anything other than display them. You should be able to take my code, add a main, and see it run.
Since it's a text file, use Scanner class.
It can be customized so that you can read the contents line-by-line, word-by-word, or customized delimiter.
The readfromfile method reads a plain text file one line at a time.
public static void readfromfile(String fileName) {
try {
Scanner scanner = new Scanner(new File(fileName));
scanner.useDelimiter(",");
System.out.println(scanner.next()); //instead of printing, take each word and store them in string array
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
This will get you started.

Input from stdin, separated values into an ArrayList to sort

I am trying to input a file into my program. The input is a file piped to "standard in".
Here is an example input:
3
&
Pink Frost&Phillipps, Martin&234933
Se quel guerrier io fossi&Puccini, Giacomo&297539
Non piu andrai&Mozart&234933
M'appari tutt'amor&Flotow, F&252905
My program is about sorting songs/mp3's in order of title, composer, and running time.
First thing I want to do is to get the topmost integer, which in the example input is "3", and store it in an integer of my own.
The next line contains the "separator" character which, as you might see, they use to separate the title, composer, and running time for each song.
The next lines are an indeterminate amount of songs with title, composer, and running time details. What I would like to do with this is to input this into either an ArrayList or a LinkedList so that I can use a comparator to mergesort these using Collections.sort().
This is what I've got so far:
public static void main(String args[]) throws IOException {
ArrayList<Song> songs = new ArrayList<Song>();
//Defines the stdin stream
BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
System.out.flush();
int k = new Scanner(System.in).nextInt();
}
So, I hope by now you know what I wish to do.
This is my query: how do I read the different values in? (i.e. the details of each song to put them into my ArrayList.)
Usually the separator and the number of fields is assumed to be known and you wouldn't put them in the file. I would do something like.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfFields = Integer.parseInt(br.readLine());
Pattern sep = Pattern.compile(br.readLine(), Pattern.LITERAL);
String line;
List<Song> songs = new ArrayList<Song>();
while((line = br.readLine()) != null) {
String[] fields = sep.split(line, numOfFields);
songs.add(new Song(fields[0], fields[1], fields[2]);
}
Collections.sort(songs);
Disclaimer: If this is homework, you have to do the way you have been shown, not just anyway which works.
Use a BufferedReader wrapping a FileReader to read the file line by line.
For each song line, use String.indexOf to find the indices of the separator char you read from the second line, and String.substring to get each part of the line as a separate string.
Use Integer.parseInt to transform the last string into an integer.
Define a Song class containing the three information about a song: title, author and time. For each song line, construct a new instance of Song and put the instance in a List<Song>.
Call Collections.sort with a comparator in order to sort your songs. Read http://download.oracle.com/javase/tutorial/collections/interfaces/order.html for information about sorting.
The documentation about all these classes and methods can be found here: http://download.oracle.com/javase/6/docs/api/

Categories