Storing data from jfilechooser - java

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:

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);
}

How to parse lines of code with multiple data types

Currently working on a program that reads in stats from football players and converts the data to binary and writes it all to a file. The problem I have been having is parsing all the different data types that the file I'm reading in contains. The file I am reading in will have the following format - lastName yearsExp position height weight 40ydSpeed team active? An example of what this will look like is the file is the following: Brady, 14, QB, 1, 210, 4.9, Patriots, true
I am wondering how to go about parsing the different data types, int, char, double, String, and boolean.
So far my program asks the user to enter a file and it catches any FileNotFoundExceptions from invalid files and loops until a valid file is entered. Then the program reads the file and stores it all into a list.
public static void main(String[] args) throws IOException {
File file;
Scanner inputFile;
Scanner readFile;
String line;
String fileName;
int x = 1;
ArrayList<String> stats = new ArrayList<String>();
do {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter the name of a " +
"file containing football player data:");
fileName = kb.nextLine();
try {
file = new File(fileName);
inputFile = new Scanner(file);
while(inputFile.hasNext()) {
stats.add(inputFile.nextLine());
}
x=2;
}
catch (FileNotFoundException e)
{
System.out.print("File not found. ");
}
}
while(x==1);
for (String s : stats) {
System.out.println(s);
}
// TODO use the following methods for writing to binary
// TODO writeUTF, writeInt, writeChar, writeInt, writeInt, writeDbl, writeByte
how to go about parsing the different data types, int, char, double, String, and boolean
In order:
int x = Integer.parseInt(s)
char x = s.charAt(0)
double x = Double.parseDouble(s)
String x = s
boolean x = Boolean.parseBoolean(s)
The current problem is tha ArrayList<String> stats = new ArrayList<String>(); forces any of the values you read to be String. If you've learned about classes, then you can create a class that models a football player: let's call it FootballPlayer as an example.
In FootballPlayer you would have many fields of different types. You would have one for lastName that is a String, yearsExp that is an int, etc.
Then, here:
while(inputFile.hasNext()) {
stats.add(inputFile.nextLine());
}
You could keep an index corresponding to what field you are trying to read. lastName could correspond to index 0, yearsExpr to 1, etc. Then, based on the index value (you could use a switch statement), you could call a different method of Scanner that returns the appropiate type, like nextInt(), if the index if 1 (for yearsExpr). After calling this appropiate method, you would assign the returned value to the corresponding field in your instance of FootballPlayer.
In the future, this whole process could be handled for you by using a library to parse the data format you're using, like a CSV parser (as it appears you data is comma-separated).
You could split the input by the , or any other common delimiter separating them, then try to parse each one by one.
String input = "Tom, 15, 6, 86.4"; // name, age, grade, mark
String[] inputs = input.split(", "); // [ Tom, 15, 6, 86.4 ]
for (String in : inputs) {
if (isInteger(in)) {
// something
} else if (isString(in)) {
// other thing
} // etc
}

Having a bit of trouble reading in a file that contains specific information in each line

So I am having trouble reading in a file. The file contains 2 integers in the first line, and the rest of the file contains Strings in seperate lines. For some reason my logic in this code, it does not seem to consume each line in the file correctly. I tried to troubleshoot this by printing out what was happening, and it seems like the second nextLine() is not even executing.
while(inputFile.hasNext())
{
try
{
String start = inputFile.nextLine();
System.out.println(start); // tried to troubleshoot here
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
System.out.println(rowsAndCols[0]); // tried to troubleshoot here
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
cell = new MazeCell.CellType[rows+2][cols+2];
String mazeStart = inputFile.nextLine(); // part where it should begin to read the rest of the file containing strings
String [] mazeRowsAndCols = mazeStart.split(" ");
MazeCell.CellType cell2Add;
Based upon your description above, only the first line contains Integers, so your while loop is wrong as it is trying to convert every line into Integers.
Split into the code into
if (inputFile.hasNextLine())
{
String start = inputFile.nextLine();
String [] rowsAndCols = start.split(" "); // part where it should read the first two integers
int rows = Integer.parseInt(rowsAndCols[0]);
int cols = Integer.parseInt(rowsAndCols[1]);
}
then a while loop for the String reading

Adding to an object array list using a file reader

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];

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.

Categories