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;
}
}
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.
I'm new to Java, and I can't seem to find exactly what I'm looking for on this website. Apologies if it has already been answered in the past!
Essentially, I'm trying to compare a user inputted string to multiple strings pre-established in the program as a "database".
As an example
System.out.println("Enter a name to check the database");
Scanner names= new Scanner(System.in);
String nameinput= names.next();
if(!nameinput.equals( *[ database]?* )
System.out.println("There is no such name, you cannot continue");
How do I check if the inputted string is not equal to the entire database individually?
I have the database set up simply as
class database
{String name, name, name, name... etc.}
I'm trying to stick to keeping things simple and using the database, if at all possible.
I understood that you have a class that contains individual names as fields. It seems like you are looking for a simple collection instead:
List<String> database = Arrays.asList("item1", "item2", "item3");
System.out.println("Enter a name to check the database");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
if (database.contains(input)) {
System.err.println("There is no such name, you cannot continue");
}
Arrays.asList simply initializes the collection with the 3 items. You can later dynamically add or remove items with database.add or database.remove.
I suggest reading about Java collections and their usage
I suggest to make a list of all the names available in the database. So database class will have a method like
public List getData ()
It will return all the available names. To make the comparison easier, you can try to have the names in the list as uppercase or lowercase using .toUpperCase() or .toLowerCase()
So when you get the input string from user, convert that string to uppercase or lowercase based on your data.
Then simply you can check if this input string is part of list using contains method.
something like,
if(!availableNames.contains(inputName))
System.out.println("There is no such name, you cannot continue");
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.
I've been trying to figure out how to create a program for a class. So far, I've gotten the rest of it down but I'm still unsure on how to do the start to it.
It requires for me to receive a name in any format: jOhn, joHN, JoHn
and convert it to John. I've been searching everywhere on how to separate them and return but I've had no luck.
Can anybody help?
This is for Java by the way.
EDIT: Not sure if I ended up doing it the right way, but I ended up with this:
System.out.println("Please type in your first name.");
String firstName = fName.next();
String partFirstName = firstName.toUpperCase().substring(0,1);
String partFirstName2 = firstName.toLowerCase().substring(1);
String correctFirst = (partFirstName + partFirstName2);
Simply in Java, without any 3rd party libraries, you can iterate over each element of an array of splitted Strings and then do:
Character.toUpperCase(user_input.charAt(0)) + user_input.substring(1).toLowerCase();
I don't know if this is what you are looking for but you could try the following:
EDIT: Thanks to Bohemian for pointing out a little bug in my code. The simplest code for the name formatting problem is Character.toUpperCase(input.charAt(0)) + input.substring(1).toLowerCase();. This is also what mhasen answered with so credit to him and also to Bohemian. Below contains the code snippet and all.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
String newInput = Character.toUpperCase(charAt(0))
+ input.substring(1).toLowerCase();
System.out.println();
System.out.println(newInput);
scan.close();
}
}
You can use Apache Commons Lang library's WordUtils.capitalize()
e.g: WordUtils.capitalize("john") will return "John".
And in order to split the string you can use split() method of String:
String input = "jOhn,JOhn,jOHn";
String[] values = input.split(",");
values will be array of String contain "jOhn","JOhn" and "jOHn"
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.