Displaying Stats with arrays in Java - 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.

Related

Java buffered reader - jump to line

I'm reading through a file like this:
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.CANCEL_OPTION) {
System.exit(1);
}
file = fileChooser.getSelectedFile();
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(file));
String line = reader.readLine();
while (line != null) {
//do stuff for each line
}
reader.close();
The file looks like this:
0 LOAD 1,3
1 LOAD 0,2
2 ADD 1,2
3 ADD 0,1
4 LSS 1,3,2
5 STOR 62,1
I've parsed it like this:
String[] actionFirstSplit = line.split(" ");
There's code associated with each line that isn't shown here. For certain lines, I'd like to jump back to a certain line number, and continue reading through the file once again. What is the best way to do this? Do I have to create another reader and skip lines until the particular line I'm interested in? I'm looking along the lines of this post, but I want to continue reading the rest of the file.
If this were my project, I'd
Create a class, perhaps called MyClass (for discussion purposes only), to hold one line's worth of data. It would have line number, String for text (command?), and a List<Integer> to hold a variable number of int parameters.
Create a List<MyClass> to hold a linear collection of objects of this class.
In my single BufferedReader, read each line, create a MyClass object, and place it in the collection.
When I needed to loop back, I simply search through my collection -- no need to re-read from a file since this is a relatively expensive task while looping through a List such as an ArrayList isn't quite so.

How to make an array of Strings to store words of a "dictionary" from a .txt file?

I need to make a dictionary that takes words from a .txt file. These words (separated line by line) need to be stored in a String array. I have already gotten to the point of separating the words and adding them to a new .txt file, but I have no idea how to add them each to a String array. There are
You need to count the lines in the file. Create an array of that size.
Then for each line in the file, read it and insert it into the array at the index[lineReadFrom].
Since you are not allowed to use ArrayList or LinkedList objects, I would suggest to save every found word "on the fly" while you are reading the input file. These is a series of steps you could follow to get this done:
1. Read the file, line by line: Use the common new BufferedReader(new FileInputStream("/path/to/file")) approach and read line by line (as I assume you are already doing, looking at your code).
2. Check every line for words: Break every possilbe word by spaces with a String.split() and remove punctuation characters.
3. Save every word: Loop through the String array returned by the String.split() and for every element that you considered a word, update your statistics and write it to your dictionary file with the common new BufferedWriter(new FileWriter("")).write(...);
4. Close your resources: Close the reader an writer after you finished looping through them, preferably in a finally block.
Here is a complete code sample:
public static void main(String[] args) throws IOException {
File dictionaryFile = new File("dict.txt");
// Count the number of lines in the file
LineNumberReader lnr = new LineNumberReader(new FileReader(dictionaryFile));
lnr.skip(Long.MAX_VALUE);
// Instantiate a String[] with the size = number of lines
String[] dict = new String[lnr.getLineNumber() + 1];
lnr.close();
Scanner scanner = new Scanner(dictionaryFile);
int wordNumber = 0;
while (scanner.hasNextLine()) {
String word = scanner.nextLine();
if (word.length() >= 2 && !(Character.isUpperCase(word.charAt(0)))) {
dict[wordNumber] = word;
wordNumber++;
}
}
scanner.close();
}
It took about 350 ms to finish executing on a 118,620 line file, so it should work for your purposes. Note that I instantiated the array in the beginning instead of creating a new String[] on each line (and replacing the old one like you did in your code).
I used wordNumber to keep track of the current array index so that each word would be added to the array at the right location.
I also used .nextLine() instead of .next() since you said that the dictionary was separated by line instead of by spaces (which is what .next() uses).

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.

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.

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