(Java) Using StringTokenizer to Read from textfile with Array - java

I'm trying to use StringTokenizer to read in data from a text file. The program I am writing is to read in various burger orders. The data I am trying to read in (toppings from burger order) is stored as a String array of size 7. It seems like everything is working fine except for when I am reading in more than one burger order from the text file and it looks like the last array of toppings replaces all the other arrays, meaning that I think my index is overriding the previous index. I tried to copy the array to an temporary array but it seems maybe I'm not doing it correctly. Any help will be appreciated.
while (infile.hasNextLine())
{
line = infile.nextLine();
StringTokenizer tokens = new StringTokenizer(value,", ");
bun = tokens.nextToken();
size = tokens.nextToken();
line = infile.nextLine();
tokens = new StringTokenizer(line,",");
index = 0;
while(tokens.hasMoreTokens())
{
burger_toppings[index] = tokens.nextToken();
temporaryBurgerToppings= burger_toppings.clone();
index++;
}
who = new Burger(size,bun,toppings);
burger.add(who);
}

To solve the issue just create a new array for each Burger order(i.e declare the array again) at the beginning of the outer while loop.

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

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

Reading a file using Scanner

I'm having some trouble understanding how Java uses Scanner to read lines from a file and was hoping to get some clarification after days of confusion.
I have a .txt file with one line that contains a name and then 5 doubles. I'm trying to figure out how I can assign each of those to a variable inside a loop so I can work with the data. My goal is to actually take the data from these lines and pass them as parameters to another method for validation, so if there's an easier way to do that, I'm all ears. I feel like I can't find a way to just iterate over each thing inside the nextLine, just over the entire line itself. I'm trying to do this without using an array, here's the relevant code snippet I have right now.
Scanner inputFile = new Scanner(file);
while (inputFile.hasNext())
{
String line = "";
accumulator++;
Scanner split = new Scanner(inputFile.nextLine());
while (split.hasNext())
{
}
stockName = inputFile.next();
shares = inputFile.nextDouble();
purchasePrice = inputFile.nextDouble();
purchaseCommission = inputFile.nextDouble();
salesPrice = inputFile.nextDouble();
salesCommission = inputFile.nextDouble();
System.out.println(stockName);
System.out.println(shares);
System.out.println(purchasePrice);
System.out.println(purchaseCommission);
System.out.println(salesPrice);
System.out.println(salesCommission);
System.out.print(line);
System.out.println("");
// checkValidity(line);
}
I'm having a hard time asking and articulating what I don't know, so any and all help is greatly appreciated... I've literally been working on this for three days and I'm at a total wall.
EDIT:
The layout of the text file looks like this
DELL: Dell Inc
125 25.567 0.025 28.735 0.025
MSFT: Microsoft
34.1 -15.75 0.012 15.90 0.013
You are almost there. You need to just remove the line:
while (split.hasNext())
{
}
This consumes all the elements given to split. You need to assign this to all the elements like stock, salesPrice etc.
So, the new snippet inside the outer while loop is
stockName = inputFile.nextLine();
Scanner split = new Scanner(inputFile.nextLine());
shares = split.nextDouble();
purchasePrice = split.nextDouble();
purchaseCommission = split.nextDouble();
salesPrice = split.nextDouble();
salesCommission = split.nextDouble();
Since, you are reading line by line, also make sure the outer while loop looks like:
while (inputFile.hasNextLine()) {
}

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).

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