I am trying to create a method that gets values of a String to create transactions of two bank accounts. I read a .txt file and saved each line in an entry of an ArrayList<String>.
Each line has its own task. Best to explain with an example .txt file:
2
Alice 50
Bob 70
1
Alice Bob 20 This is my reason for the transaction.
Line 1: first line marks the amount of accounts that are involved in the transactions followed.
Line 2-3: The following two lines are two accounts with the given balance.
Line 4: indicates the amount of transactions followed.
Line 5: meant to be like: Bob transfers amount 20 to Alices account with an optional
note ("This is my reason for the transaction.")
This is how i approached the problem: I have created a class Account which has a String holder and a int balance. I managed to separate the lines 2-3 by using a the String.split(" ") method. But the next problem I could not handle is the transaction followed. I created a class called Transaction with one of the following constructors.
String receiver;
String sender;
int amount;
int timestamp;
String note;
public Transaction (String receiver, String sender, int amount, String note) {
this.receiver = receiver;
this.sender = sender;
this.amount = amount;
this.note = note;
}
The Problem I have is that I want to perform the transaction(s) but do not know how to handle the note part of the line 5. I even have no idea how to go through my ArrayList<String> linesOfFile and mark the parts where it creates an account (if not existing) and then do the part with the transactions for each line that is indicated by the Integer above. I managed to create the accounts though but do not know how to go on.
My idea would be creating an Integer that has the same size as the number of line 1. After that I go through the file and create (if not existing) the accounts with the given balances. After each line which marks the accounts I decrement the Integer until it is 0 and end the loop. But After that I am completely lost. Maybe I could create a second loop that starts at the number that indicates the amount of transactions (line 4) and go through them until end of List?
ANSWERED: And how is it possible to set the last part of the transaction as one String element?
answer: just used a limit at .split() method.
Sample code would be:
ArrayList<Account> accounts;
ArrayList<String> linesOfFile = readFile("file.txt");
int count = 0;
for (String line : linesOfFile) {
if (Character.isDigit(line.charAt(0))
count = Integer.parseInt(line);
if (count != 0) {
String[] accountDetails = line.split(" ");
if (!accountExists(new Account (accountDetails[0], accountDetails[1]))) {
accounts.add(new Account(accountDetails[0], accountDetails[1]);
}
count--;
}
// This is the part I want to add for the Transactions.
}
Thanks in advance!
You won't like this answer but may I ask for the use case for this?
Is this a file you create in your program somewhere else (I. E. Is this a hobby program you use for practising and the file is what could alternatively be done in a database instead ?) or is that from a real world business case where you need to import an incoming file into your system?
The reason why I'm asking is, that if possible, you could add tags in the file upon creation, to identify the fields you are reading. Alternatively of course, you should use a DB.
Related
I have a .CSV file with rows for [ID], [NAME], [LASTNAME], [EMAIL], [GENDER]. There are 1000 entries.
Out of those five rows I have to:
Find the total of people on the list. (using a for loop?)
Show the first 10 names (name, lastname).
Show 3 RANDOM names.
Only display emails. (Doable with the current code)
Display the first letters of their last name.
Add a random number behind their last name.
Can someone make an example, please?
As a Java beginner I really can't seem to find an answer to this. I have searched everywhere and i think im going crazy.
I have imported the .csv file to my java eclipse, using the following code, currently it only displays the ID's.
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class test111 {
public static void main(String[] args) {
String fileName="test.csv";
File file = new File(fileName);
try {
Scanner inputStream = new Scanner(file);
inputStream.next();
while (inputStream.hasNext()) {
String data = inputStream.next();
String[] values = data.split(",");
System.out.println(values[0]);
}
inputStream.close();
System.out.println("e");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
In order to take every value you have to do something like this:
int id = Integer.parseInt(values[0]);
String name = values[1];
String lastName = values[2];
String email = values[3];
String gender = values[4];
Yours is a lesson in why you shouldn't blindly copy code without reading it, researching it and understanding it.
Look at line 15 from your own code. What do you think is going on here?
String[] values = data.split(",");
You've read a line from your CSV file into a field called data and now you're calling the .split method with a comma as a parameter to break up that line into tokens wherever it finds a comma. Those tokens are being placed into the cells of an array called values.
Why are you only getting your ID attribute? Look at this line:
System.out.println(values[0]);
We just established that all tokens have been placed in an array called values. Let's look at the attribute key you provided:
[ID], [NAME], [LASTNAME], [EMAIL], [GENDER]
Hmm... if printing values[0] gives us the ID, I wonder what we'd get if we... oh, I don't know... maybe tried to print from a different element in the array?
Try:
System.out.println(values[1]);
System.out.println(values[2]);
System.out.println(values[3]);
System.out.println(values[4]);
See what you get.
Coding is about trying things in order to learn them. Knowledge doesn't magically become embedded in your head. To learn something, you have to practice repeatedly, and in doing so, you're going to make mistakes -- this is just how it goes. Don't give up so easily.
working on my current lab and seemed to have run into a slight roadblock. I have never used the split() method up until now and am unsure on how to remedy my problem. Here is a snippet of my code to get started explaining.
Map<Integer, Employee> employeeMap = new HashMap<>();
while (true)
{
line = scanner.nextLine();
if (line.startsWith("$"))
{
break;
}
String[] employeeTracker = line.split(" ");
Employee employee = new Employee(
++empCount,
employeeTracker[0],
employeeTracker[1],
employeeTracker[2],
Double.parseDouble(employeeTracker[3]),
Integer.parseInt(employeeTracker[4]), Boolean.parseBoolean(employeeTracker[5]));
employeeMap.put(employee.getId(), employee);
}
Original example input: (this was when my Employee employee = new Employee had 4 arguments for input. I have now increased it to 6 for 2 additional inputs needed from a new class being added.
John Smith 1234567 10.55
New input I'm trying to get to work.
*John Smith 1234567 10.55 1 true
The issue currently is now that I have made the program accept this new input, I need it to also just work when the old type of input is put in (with just 4 arguments). My first thought is to give some dummy value to those other 2 last arguments when this occurs to prevent crashing, but I have had little luck doing so. Thus, I search for any welcoming suggestions.
Thanks in advance! I would be glad to post any additional code or answer any other questions as necessary.
You can use the length of the employeeTracker array to test what the input is
if (employeeTracker.length >= 6) {
// new inoput
}
else {
// old input
// use dummy values
}
I am a newbie to programming and was learning Java myself from Core Java .
The book mentioned a few lines about reading csv files in Java and storing its contents into a data-structure .
So while trawling the internet , I came across the following problem :
There is a school which has the following actors : Faculty , Staff and Students
Faculty has the following attributes : Name , Phone Number , E-Mail ID Address , Department , No. of Research Papers
Students has the following attributes : Name , Phone Number , E-Mail ID , Address , Roll No. , GPA
Staff has the following attributes : Name , Phone Number , E-Mail ID , Address , Department , Salary
Now , the all this data is stored in a single csv file in the following manner :
Student,Harry Potter,9999999,hp#hogwarts.magic,Hogsmeade Street,1,4.0
Staff,Argus Filch,888888,arg#mrsnorris.com,Hogwarts,Cleaning,5000
Faculty,Snape,555555,snape#snivellus.com,Hogwarts,Potions,40000
.
.
.
.
Now , I need to read the data from the cs file , in Java , and store it into a linked list such in the following order : Faculty Records followed by Staff Records followed by Student Records
My Code :
The code that I have written till now is :
import java.io.*;
import java.util.*;
public class readCSV {
public static void main(String[] args) throws FileNotFoundException
{
Scanner scanner = new Scanner(new File("CSV.csv"));
scanner.useDelimiter(",");
while (scanner.hasNext())
{
// Read the tokens and store them into a Linked List
}
scanner.close();
}
}
My Problem :
Can someone help me out ? I do not want to use any library to parse the csv and also want to make my own linked list from scratch -- it will be a good practice
My main problem is to read from csv and store the data into a linked list . An illustrative code snippet would go a long way
Disclaimer: This is not a homework question . I am self-learning Java
For linked lists I'd suggest reading one of Robert Sedgewick's Algorithm books. (Implementing a linked list itself is not going to be too hard if a) you know some Java and b) you know how linked lists work.) I expect there are plenty of example on the web, too.
Having written your own linked list implementation (for learning): throw it away and don't use it in real programs. Seriously. The existing library implementations are going to be way better; writing real-world collections libraries is a serious undertaking.
Parsing CSV is more complicated than is sounds if your data (text) can contain commas and quotes that are not CSV delimiters (which is usually true in real data).
However a naive implementation might be:
Open the file using a LineNumberReader.
Call readLine() in a loop until you get back null (no more lines).
Split each line read with line.split(",").
Process each line's fields.
You can parse the file with something like this:
Scanner scanner = new Scanner(new File("CSV.csv"));
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if (line.isEmpty()) {
continue;
}
String[] parts = line.split(",");
String name = parts[1];
String number = parts[2];
String email = parts[3];
String address = parts[4];
switch (parts[0]) {
case "Faculty":
String department = parts[5];
String papers = parts[6];
// add to list
break;
case "Student":
String roll = parts[5];
String gpa = parts[6];
// add to list
break;
case "Staff":
String department = parts[5];
String salary = parts[6];
// add to list
break;
}
}
I have design the search method. According to my requirement, If a user wants to search a customer’s record, he/she can input the customer’s family name or given name into the name text field and then click the search button. The following two screen shots show an example of the events before and after button click (with input the name to be searched is Lee)
And below is the code for searching. It is working fine but I want to make it better?
private void search()
{
String studentName=CNameTextField.getText();
String record="";
int count=0;
for(int i=0; i<myList.size();i++)
{
String name=myList.get(i).getName();
String [] splitName= name.split(" ");
if(studentName.equals(splitName[0]) || studentName.equals(splitName[1]))
{
count++;
record=record+"\n"+myList.get(i).toString();
}
display.setText("");
display.append(count + " result(s) found for "+ studentName);
display.append("\n "+ record);
}
}
So you've basically got a list of String items, and you're searching through all of them for the value?
My recommendation would be to create Objects for each line in your DisplayArea, rather than Strings. For example, when you read in the input file for your DisplayArea, do the split() for each line and create objects of type Customer that have fields called ID, name, room, etc. This would be better OO programming anyway - Strings don't really have any meaning, whereas a Customer has meaning.
If you do this, in the search you can simply loop over all the Customers in the list, asking whether the name.equals(customer.getName()); This would remove the need to split the line every time you search.
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.