How to get information from a CSV file in Java - java

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.

Related

Storing A String From A Text Document And Printing It To The Screen

So I have this code so far:
import java.util.*;
import java.io.*;
public class EmailMerge {
public static void main(String[] args) throws IOException {
Scanner templateReader = null;
Scanner peopleReader = null;
PrintWriter out = null;
String template = "";
ArrayList people = new ArrayList();
try {
templateReader = new Scanner(new FileInputStream("template.txt"));
peopleReader = new Scanner(new FileInputStream("people.txt"));
while(templateReader.hasNext()) {
//System.out.print(templateReader.next());
template = templateReader.next();
}
System.out.println(template);
}
catch(FileNotFoundException e)
{
System.out.println("File(s) not found...");
System.exit(0);
}
}
}
I have a text document called template.txt that contains this:
Dear <<N>>,
Because you are <<A>> years old and <<G>>, we have a
free gift for you. You have absolutely nothing to buy;
just pay the shipping and handling charge of $9.99. To
claim your gift, call us immediately.
Thank you,
Office of Claims Department
and I have another text document called people.txt that contains names and ages of people like so:
John, 38, Male
Mary, 22, Female
so on and so forth...
What I have to do is go through all the names on the list and make a personalized message using the template. Then I have to save each to a unique text document(i.e. John.txt). What I want to do is store the names on the list into an ArrayList, I called people, and then store the template into a string, which I called template.
However, my issue comes in when I try to print out the template. I can't tell if I am storing it wrong of if there is a better way to print it out, but when I use this code I just get "Department" printed to the screen. I need to have the whole thing stored in the String template and be able to print it to the screen in its proper format like it is above.
Please Help, Thanks A Bunch!!
UPDATE:
Thank you guys so much for the help!
One more question. I am finally at the end of the project and I have stored all of the necessary information into a few ArrayLists, however when I try to print out the template it will work, but it does it about a 1000 times. Here is the loop I am using:
for(int j = 0; j < people.size(); j++){
for(int i = 0; i < names.size(); i++){
System.out.println(template.replace("<<N>>", names.get(i)).replace("<<A>>", ages.get(i)).replace("<<G>>", genders.get(i)));
}
}
I stored all of the names/ages/genders into the appropriate ArrayList. Thanks again!
You're replacing the template String variable each time instead of updating it (appending). Try the code below:
template += templateReader.next();
Or better - as stated by Luiggi in the comment - a StringBuilder:
StringBuiler builder = new StringBuilder("");
while(templateReader.hasNext()) {
//System.out.print(templateReader.next());
builder.append(templateReader.next());
}
template = builder.toString();
StringBuffer offers better performance than the + operator, so whenever you append Strings in a loop - like in this example - it's better to use it.
Use a StringBuilder to save the whole template in a String :
StringBuilder sb = new StringBuilder();
while(templateReader.hasNext()){
//System.out.print(templateReader.next());
sb.append(templateReader.next());
}
template = sb.toString();
It is faster than String concatenation especially if your template is long.
You can read the template.txt all at once using
String template = new Scanner(new File("template.txt")).useDelimiter("\\Z").next();
System.out.println(template);
useDelimiter("\Z") is used to read whole file at once.
I suggest breaking this into small parts that are each implemented as a separate method:
One method to read in the file with the names and other data
One method to read in the template
One method to replace the "fields" in the template with the correct data
Designing your code this way will allow you to test each piece individually and make it easier to track down logic errors.

Java NetBeans: Why does my string array terminate prematurely?

I found the problem. Apparently, there were random spaces in some of the names in the csv file, which was causing breaks at the 257th entry, as well as several others later on. So, I just took out the spaces and everything works fine now. Thanks to all who tried to help.
I have this code that reads from a csv file, puts the values in String array, and prints them for me to see. It runs fine until it reaches the 257th member of the array (each member has 3 values: last name, first name, and birth year). Here is a functioning version of the code:
package testing.csv.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//.csv comma separated values
String fileName = "C:/Users/Owner/Desktop/Data.csv";
File file = new File(fileName); // TODO: read about File Names
try {
Scanner inputStream = new Scanner(file);
inputStream.next(); //Ignore first line of titles
while (inputStream.hasNext()){
String data = inputStream.next(); // gets a whole line
String[] values = data.split(",");
System.out.println(data);
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now, when I change the line
System.out.println(data);
To this:
System.out.println(values[2]);
What I expected to happen was for only the birth years (3rd column) to be printed for every person in the array. However, it only prints out until the 257th person's birth year (out of over 18,000), and gives me the following error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at testing.csv.files.Test.main(Test.java:22)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
The "java: 22" seems to be referring to the above snippet of code I posted above that I changed. I am not really sure what the problem is. If my syntax is wrong, why did it print at all? The only thing I can think of is that perhaps a string array can only handle 257 different people each with their own 3 values. If that were the case, then I would need some kind of larger version of string to hold all of my data. Has anyone encountered this problem before? Is the problem somewhere in my syntax and loop?
If there are only two things in the values array, then the highest location that you can index into is 1.
For arrays, you can only index into size - 1 spots; that is, if your array was size ten, you could index into a location 9, or more verbose: array[9].
Change your indexing statement to this:
System.out.println(values[1]);
You might want to see the 257th record in the csv file. Would the split method create three tokens for it? If it should result in less than three tokens and you try to print the third token by typing
System.out.println(values[2]);
you will get an ArrayIndexOutOfBoundsException.
Change:
String data = inputStream.next(); // next() can read the input only till the space
to:
String data = inputStream.nextLine(); // nextLine() reads input including space between the words
Also better way is to iterate the array instead acess through index may be particular line in csv not containing the third column.

Java - Reading in value from text

OK so I have read plenty of examples on here dealing with reading in lines from a text file and splitting them up but im not quite sure I understand how to do it in my situation. I have a file that is basically separated into three columns as follows:
START 5000
FIND A
PLUS B
SAVE C
STOP
A, INT 69
B, INT -420
C, CRAZY 008484342
What I am trying to do is read in this .txt file containing the above information. I figured reading in the file line by line would be best, then splitting it into the correct columns. The problem that I am having is the fact that the 1st column is not always here. It is an optional one. If they were all filled in, im almost positive I could just use use something like
String[] array1 = myLine.split(",");
Another idea I had was to split the line based on ,'s then split the line again based on " " but im not exactly sure how to do this. Maybe somthing like
String[] array1 = myLine.split(",");
String[] array2 = array1[1].split(" ");
Also, is there any way to just read in the file and store each row into like (String, String String) then just check for ints vs strings? Maybe in a try catch? or like:
Scanner input = new Scanner(File);
while(input.hasNext()){
String str = input.next();
try{
b = Integer.parseInt(str);
}
I am not sure if this is as hard as a task as im making it but maybe so... Any help with this topic would be appreciated.
After looking over some more code, I have the following to start:
public static void main(String[] args) {
String file ="TEST.txt";
try{
FileReader input = new FileReader(file);
BufferedReader bufferReader = new BufferedReader(input);
String line;
while ((line = bufferReader.readLine()) != null) {
// Is this where I would attempt to split the lines?
System.out.println(line);
}
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
So with this, I am successfully reading in the file and displaying the information back to the output console. Now for separating the lines... Ill be posting my work as I go, any help and or suggestions would be appreciated! Also thank you to those who have already commented with helping to split the stings, ill be attempting this now!
You can combine both expressions and only checked the array's length. e.g.:
String[] array = line.trim().split("[, ]+");
switch(array.length) {
case 2:
// do something
break;
case 3:
// do something
break;
default:
// something wrong
break;
}
The trim() in the line is for avoid empty string in the first element array.
Use split(" +") which will split on any numbers of spaces. This works because split handles regex. If you want to split on any type of whitespace you can also use split("\\s+). After you get the array check if it has 2 or 3 elements and handle it accordingly.
Well ... I don't have the time yet for a long answer. But I'd recommend you to read a little bit about regular expressions (RegEx) and how it is used in java ... I am sure this will help you with this problem and a huge amount of future problems like this ...
Try this: http://www.vogella.com/articles/JavaRegularExpressions/article.html ... of this http://docs.oracle.com/javase/tutorial/essential/regex/ ... if the first one does not help ;)

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.

Read the first word of each line from a text file and then populate to Combo box

I have college project where i have to read the first word of every line from text file which looks as follow:
23123123213 Samuel classA
23423423423 Gina classC
23423423423 John classD
The text file will be updated with through 3 JTextField which i am able to figure out.
but now i have to populate the JCombobox with first word(23123123213,23423423423 and 23423423423) of all the lines.
I am new to java, i dont even have hint of how about doing it.
I know how to read and write to text files.
Please could someone help me do this?
The code so far i came up with is as follows:
import java.io.*;
public class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("RokFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
String[] delims = strLine.split(" ");
String first = delims[0];
System.out.println("First word: "+first);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
With u guys help I was successfully able to extract the first string from each line
but now how could i populate it in Jcombobox, I mean should i save it somewhere first?
Thanks in Advance
I'm not "down" with Java, however I can give you a few pointers:
You can read files, and presumably can read a line.
Each line is (presumably) separated with spaces so what you need to look up is a String.split function
Once you've split a string you will be able to use array index 0 to get the information you need.
Then it's just a case of adding split_string[0] to the JComboBox.
The documents are a great help:
String
JComboBox
You can get the first word using String.split(), or by using indexOf and substring.
There is a tutorial about JComboBox.
The Java Swing classes are based on Model/View, so you have to fill the strings into the Model of the JCombobox.
EDIT: In response to your edit, suppose you have retrieved the values. Then you can indeed save them to a specific data structure. It would be preferable to make the code that retrieves those values into a separate method. The values returned from that method (in, for example, a List<String>) can then be put into the JComboBox.
If you know how to read lines from a text file you can split each line by a delimiter, using the String.split function. In that case you get an array, with which you can get the first string by a normal array indexer, the [] operator that is.
String hello = "Hello world";
String[] delims = hello.split(" ");
String first = delims[0];
To answer your edit, you populate the JComboBox using one of its constructors, for instance the one that takes an Object array, or using the JComboBox.addItem(Object) function.
The latter has an example. Regarding the one with the constructor you can either build an array of objects yourself, or use an arraylist to which you add all your elements and then get an array using the ArrayList.toArray() function.

Categories