Counting words from a file - java

for this program I have to write I'm given an input file of strings that has a line (or lines) of text, for example: "The high HIGH cat High jumped (WOW 6SOFT)". From this line I have to scan the file, count the number of times a word appears (regardless of capitalization), and then output it to a formatted file. If a digit comes before a word, the word should not be counted. The format has to be started with the count right justified in three spaces, followed by another space, followed by the word counted in lower case.
package InClass;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class CountWords {
public static void main(String[] args) {
try {
File inputFile = new File("input.txt");
Scanner scanner = new Scanner(inputFile);
File outputFile = new File("output.txt");
PrintWriter writer = new PrintWriter(outputFile);
boolean next = scanner.hasNext();
ArrayList<String> inputWords = new ArrayList<String>();
ArrayList<String> outputWords = new ArrayList<String>();
while (next) { // Adds all the strings to an array list
inputWords.add(scanner.next());
for (int i = 0; i < inputWords.size(); i++) {
inputWords.get(i).toLowerCase();
}
}
while (next) {
for (int i = 0; i < inputWords.size(); i++) {
String word = inputWords.get(i);
int count = 1;
if (!Character.isDigit(word.charAt(0))) {
outputWords.add(inputWords.get(i));
if (outputWords.contains(word)) {
count++;
}
} else {
inputWords.remove((i));
}
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
}
}
scanner.close();
writer.close();
} catch (FileNotFoundException e) {
}
}
}
My tester file is giving me an error saying there is a NoSuchElementException for only one of the tester classes, which is testing two words. Here is the test class giving the error"
#Test
public void testTwoWords() {
try {
File inputFile = new File(INPUT);
File outputFile = new File(OUTPUT);
// If assert fails it is (usually) because the file was (wrongly)
// left open in an earlier run.
// Using a file manager application (e.g. explorer), go to project
// directory and delete it.
// Make sure that your program closes these files before ending.
if (inputFile.exists()) {
assertTrue("Your program left \"" + INPUT
+ "\" open in a previous test.", inputFile.delete());
}
if (outputFile.exists()) {
assertTrue("Your program left \"" + OUTPUT
+ "\" open in a previous test.", outputFile.delete());
}
// create INPUT file
PrintWriter input = new PrintWriter(inputFile);
input.println("King");
input.println("");
input.println("");
input.println("");
input.println("hill");
input.close();
// invoke program
CountWords.main(null);
// verify OUTPUT file exists and is empty
assertTrue("Output file doesn't exist", outputFile.exists());
Scanner output = new Scanner(outputFile);
String actual = output.nextLine();
assertEquals("Incorrect result", " 1 king", actual);
actual = output.nextLine();
assertEquals("Incorrect result", " 1 hill", actual);
assertFalse("There should be no more data", output.hasNext());
output.close();
// delete I/O files
assertTrue("Input file could not be deleted", inputFile.delete());
assertTrue("Output file could not be deleted", outputFile.delete());
} catch (IOException e) {
fail("No exception should be thrown");
}
}
Finally, my other testers are saying "Your program left "input.txt" open in a previous test". Any idea why? Thank you tons in advance!

The for loop for your outputWords is using the i loop counter instead of j.
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(i);
writer.printf("%3s" + "%1s\n", count, word);
}
Change that to
for (int j = 0; i < outputWords.size(); j++) {
word = outputWords.get(j);//NEED TO USE J HERE
writer.printf("%3s" + "%1s\n", count, word);
}
The reason the other tests are failing is because you are apparently supposed to delete the output files after each test is run.

Related

How to check if a certain word is contained in a text file?

I'm trying to check every occurrence of these words- Calculate, EXE, I/O, Yield, and Out. I read in a file and store the data in an object called process. All the data has been correctly stored in the object. The Method prep finds every occurrence of these words. The only problem is all the
words work except I/O the first occurrence never shows up.
Code-
public void contentArray(Process x)
{
for(int i=0; i<x.getListInfo().size(); i++)
{
System.out.println(x.getindex(i));
}
}
public void prep(Process x)
{
System.out.println("******************");
String xo ="oo";
while(xo!="EXE")
{
for(int i=0; i<x.getListInfo().size(); i++)
{
String processor = x.getindex(i);
if(processor.equals("I/O"))
{
System.out.println("I/O " + i );
xo="I/O";
}
else if(processor.equals("CALCULATE"))
{
System.out.println("Calculate "+ i);
xo="CALCULATE";
}
else if(processor.equals("YIELD"))
{
System.out.println("YIELD " + i);
xo="YIELD";
}
else if (processor.equals("OUT"))
{
System.out.println("Out " + i);
xo="OUT";
}
else if (processor.equals("EXE"))
{
System.out.println("EXE " + i);
xo="EXE";
}
}
}
}
import java.io.*;
import java.util.*;
public class FileReader {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in);
int fileNum = 0;
String filename;
int runtime = 0;
int memory = 0;
int counter = 0;
String name = "";
int filecounter = 0;
String x = "";
ArrayList<Process> allfiles = new ArrayList<Process>();
System.out.println("How many files do you have");
x = in.nextLine();
while (filecounter < Integer.parseInt(x)) // number of files
{
System.out.println("enter file name");
filename = in.nextLine();
filecounter++;
File file = new File("C:\\Users\\documents\\git\\" + filename);
Scanner s = new Scanner(file);
//Scanner s = new Scanner(new File(filename));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()) {// takes in all file values
list.add(s.next());
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals("Name:")) {
name = list.get(i + 1);
System.out.println(name);
//list.remove(i);// removes name
//list.remove(i+1);// removes file name
}
if (list.get(i).equals("runtime:")) {
runtime = Integer.parseInt(list.get(i + 1));
System.out.println(runtime);
//list.remove(i); //removes runtime
//list.remove(i+1); //removes runtime value
}
if (list.get(i).equals("Memory:")) {
memory = Integer.parseInt(list.get(i + 1));
System.out.println(memory);
//list.remove(i);//removes memory
//list.remove(i+1); //removes memory value
}
}
counter++;//pid starts from 1 and goes up
Process p = new Process(name, counter, runtime, memory, ProcessState.New, list);
allfiles.add(p);
s.close();
}
Scheduler schedulerQ = new Scheduler();
schedulerQ.contentArray(allfiles.get(0));
schedulerQ.prep(allfiles.get(0));
}
}
Output-
Input test file
Name: lo
Total Runtime: 100
Memory: 90
I/0 90
CALCULATE 80
I/O 90
CALCULATE 20
CALCULATE 100
CALCULATE 100
YIELD
YIELD
OUT
EXE
My Error: the error occurs never takes in first I/O !!!!!!!!!!!
Output from console:
Calculate 9
I/O 11
Calculate 13
Calculate 15
Calculate 17
YIELD 19
YIELD 20
Out 21
EXE 22
The input file seems to have I/0 in the first occurrence and not I/O. Could you check the input file again?

Is it possible to write a text file in such a way that when read by the Java compiler, it will add a line break at certain points?

For my Java class, I'm working on a project that is essentially a database for MTG cards. I have to read from a file as part of the project, so I am reading the card information from a file, and then splitting the lines to put each different type of information together to form different object classes for the different types of cards. The main nitpicky issue I'm running into right now is that I need the card text to be on one line in the text file so I can read it line by line, but I'd prefer if it weren't all on one line when I print it to the console. Is there any way to add a character combination into the text of the file itself that will tell my compiler, "line break here," when it reads that, or am I out of luck? I know I could just use \n in the code to achieve this, but as I am looping through the file, there is no way to do so properly that I know of, as not every card's text needs line breaks inserted. If it matters, this is the chunk of my code that deals with that:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class MTG {
public static void main(String[] args) {
int creatureLength = 4;
//Prompt User
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to the Magic: the Gathering card database. This tool currently supports Rare and Mythic Rare cards from the Throne of Eldraine Expansion.");
try {
System.out.println("\nSelect the card type you'd like to view.");
System.out.println(""
+ "(1)Creatures\n"
);
int choice = Integer.parseInt(sc.next());
//Choose type
//Creatures
if(choice == 1){
Creature[] creatures = creatureGen("textfiles/Creatures.txt", creatureLength);
System.out.println("\nViewing creatures. Which card would you like to view?: \n");
for(int k = 0; k < creatureLength; k++) {
System.out.println(
"(" + (k + 1) + ") " + creatures[k].getName());
}
int creatureChoice = Integer.parseInt(sc.next());
try {
System.out.println("\n" + creatures[(creatureChoice - 1)]);}
catch(Exception e) {
System.out.println("Input was not a specified number. Exiting...");
}
}
}
catch(NumberFormatException ex){
System.out.println("Input was not a specified number. Exiting...");
}
sc.close();
}
//Read Creature text file
public static Creature[] creatureGen(String path, int length) {
Creature[] creatures = new Creature[length];
try {
FileReader file = new FileReader(path);
BufferedReader reader = new BufferedReader(file);
String name[] = new String[length];
String cost[] = new String[length];
String color[] = new String[length];
String type[] = new String[length];
String cTypes[] = new String[length];
String tags[] = new String[length];
String text[] = new String[length];
int power[] = new int[length];
int toughness[] = new int[length];
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
name[i] = line.split("\\|")[0];
cost[i] = line.split("\\|")[1];
color[i] = line.split("\\|")[2];
type[i] = line.split("\\|")[3];
cTypes[i] = line.split("\\|")[4];
tags[i] = line.split("\\|")[5];
text[i] = line.split("\\|")[6];
power[i] = Integer.parseInt(line.split("\\|")[7]);
toughness[i] = Integer.parseInt(line.split("\\|")[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
reader.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + path);
}
return creatures;
}
}
The Creature object class essentially just stores the data that I am putting into it with the creatureGen method. A sample line from the text file I am reading from looks something like this:
Charming Prince|1W|White|Creature|Human Noble||When Charming Prince enters the battlefield, choose one — • Scry 2. • You gain 3 life. • Exile another target creature you own. Return it to the battlefield under your control at the beginning of the next end step.|2|2
It would be ideal to be able to insert line breaks after each of the bullet points in this card, for example, but as I said earlier, I need the text to be in one line for my loop to read it. Is there any way around this when I print this back to the console? I appreciate any help.
Just replace those bullet points with line breaks :
text[i] = line.split("\\|")[6].replaceAll("•","\n");
Also, you should not split each time you need an element, put the result of line.split("\|") in a String[] variable and use it afterwards.
for (int i = 0; i < length; i++) {
String line = reader.readLine();
if(line != null) {
String[] elements = line.split("\\|");
name[i] = elements[0];
cost[i] = elements[1];
color[i] = elements[2];
type[i] = elements3];
cTypes[i] = elements[4];
tags[i] = elements[5];
text[i] = elements[6].replaceAll("•","\n");
power[i] = Integer.parseInt(elements[7]);
toughness[i] = Integer.parseInt(elements[8]);
creatures[i] = new Creature(name[i], cost[i], color[i], type[i], cTypes[i], tags[i], text[i], power[i], toughness[i]);
}
}
Finally, about vocabulary, the compiler is not reading your file. The compiler translates your code into binary instructions for the processor (to summarize).
Your file is read at runtime.

Java - retrieve file, calculate, output to another file?

I'm new here so please excuse me if I make a mistake with the question asking process. I have researched my question for the last week and a half and haven't found what I'm looking for (although I feel like the answer is very close). I'm a student and have been working on an assignment using Eclipse for my Java class. I have written a code that takes information from one file, uses it in a calculation and now I need to output it into another file. This is where I am having difficulty. This is my code so far:
import java.util.Scanner;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.NoSuchElementException;
import java.util.ArrayList;
public class Program6 {
private Scanner input;
private ArrayList<Double> payRoll = new ArrayList<>();
public static void main(String[] args) {
Program6 myObject = new Program6();
myObject.openFile();
myObject.readFile();
myObject.calculateRecords();
myObject.closeFile();
}
public void openFile() {
try {
input = new Scanner(Paths.get("Program6.txt"));
} catch (IOException ioException) {
System.err.println("Error opening file. Terminating.");
System.exit(1);
}
}
public void readFile() {
try {
while (input.hasNext()) {
payRoll.add(input.nextDouble());
}
} catch (NoSuchElementException elementException) {
System.err.println("File improperly formed. Terminating.");
} catch (IllegalStateException stateException) {
System.err.println("Error reading from file. Terminating.");
}
}
public void calculateRecords() {
System.out.printf("%10s%25s%15s%19s", "Before Payroll",
"Raise Percent",
"Raise Amount",
"After Payroll\n");
double raisePercent;
double raiseAmount;
double totalBeforePayroll = 0;
double totalAfterPayroll = 0;
for (int i = 0; i < payRoll.size(); i++) {
if (payRoll.get(i) > 70000) {
raisePercent = 4;
} else if (payRoll.get(i) > 50000) {
raisePercent = 7;
} else {
raisePercent = 5.5;
}
raiseAmount = payRoll.get(i) * raisePercent / 100;
System.out.printf("%12.2f%21.1f%18.2f%17.2f%n",
payRoll.get(i), raisePercent, raiseAmount, payRoll.get(i) + raiseAmount);
totalBeforePayroll += payRoll.get(i);
totalAfterPayroll += payRoll.get(i) + raiseAmount;
}
System.out.printf("%nTotal amount of raises: $%,.2f%n",
totalAfterPayroll - totalBeforePayroll);
System.out.printf("Average raise percent : %.0f%%",
(totalAfterPayroll - totalBeforePayroll) * 100.0 / totalBeforePayroll);
System.out.printf("%nAverage raise amount : $%,.2f%n",
(totalAfterPayroll - totalBeforePayroll) / payRoll.size());
}
public void closeFile() {
if (input != null)
input.close();
}
}
Assuming you want to output just the payroll amount after adding the raise amount.
You can write a void method writeFile() in which you loop through your list and append every entry to an empty file.
For this I'm going to be using the BufferedWriter class, but you are free to chose whatever class you like. I'm going to proceed with the BufferedWriter example though.
So what we need to do in our writeFile method is setting up the bufferedwriter. This is done like this:
BufferedWriter b = new BufferedWriter(new FileWriter("path here" + System.getProperty("file.separator") + "filename.txt"));
Replacing "path here" by wherever you want to save your file. One example would be to replace it by System.getProperty("user.dir") which is the users working directory.
System.getProperty("file.seperator") would be a \ in Windows. But using System.getProperty("file.separator") will make it work on different systems as well.
So:
BufferedWriter bw = new BufferedWriter(new FileWriter(System.getProperty("user.dir") + System.getProperty("file.separator") + "filename.txt"));
Now you can loop through your list and append every entry to the writer:
for (int i = 0; i < payRoll.size(); i++){
bw.append(payRoll.get(i));
}
After that you can and should "close" the bufferedwriter using:
bw.close();
The method would look something like this:
BufferedWriter b = new BufferedWriter(new FileWriter("path here" + System.getProperty("file.separator") + "filename.txt"));
for (int i = 0; i < payRoll.size(); i++){
bw.append(payRoll.get(i));
}
bw.close();

how to link a main class to a jframe form in java using netbeans

Good day!
I have created a code using Netbeans and it executes the processes just fine.
Now, i want my input to given and output to be displayed through a user interface. I have then created a 2 Jframes, 1 to collect the user's input and the other to display the results after execution by the code.
But, i am unable to link the interface to the main class(called NgramBetaE) as i am not aware of how i can do so.
I highly welcome suggestions.
The main class in its entirety is;
package ngrambetae;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
/**
*
* #author 201102144
*/
public class NgramBetaE {
static LinkedList<String> allWords = new LinkedList<String>();
static LinkedList<String> distinctWords = new LinkedList<String>();
static String[] hashmapWord = null;
static int wordCount;
public static HashMap<String,HashMap<String, Integer>> hashmap = new HashMap<>();
public static HashMap<String,HashMap<String, Integer>> bigramMap = new HashMap<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//prompt user input
Scanner input = new Scanner(System.in);
//read words from collected corpus; a number of .txt files
File directory = new File("Corpus");
File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"
int lineNumber = 0;
String line;
String files;
String delimiters = "[()?!:;,.\\s]+";
//reading from a list of text files
for (File file : listOfFiles) {
if (file.isFile()) {
files = file.getName();
try {
if (files.endsWith(".txt") || files.endsWith(".TXT")) { //ensures a file being read is a text file
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
hashmapWord = line.split(delimiters);
//CALCULATING UNIGRAMS
for(int s = 0; s < hashmapWord.length; s++){
String read = hashmapWord[s];
allWords.add(read);
//count the total number of words in all the text files combined
//TEST
wordCount = 0;
for (int i = 0; i < allWords.size(); i++){
wordCount ++;
}
}
//CALCULATING BIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length -1; s++){
String read = hashmapWord[s];
final String read1 = hashmapWord[s + 1];
HashMap<String, Integer> counter = bigramMap.get(read);
if (null == counter) {
counter = new HashMap<String, Integer>();
bigramMap.put(read, counter);
}
Integer count = counter.get(read1);
counter.put(read1, count == null ? 1 : count + 1);
}
//CALCULATING TRIGRAM FREQUENCIES
for(int s = 0; s < hashmapWord.length - 2; s++){
String read = hashmapWord[s];
String read1 = hashmapWord[s + 1];
final String read2 = hashmapWord[s + 2];
String readTrigrams = read + " " + read1;
HashMap<String, Integer> counter = hashmap.get(readTrigrams);
if (null == counter) {
counter = new HashMap<String, Integer>();
hashmap.put(readTrigrams, counter);
}
Integer count = counter.get(read2);
counter.put(read2, count == null ? 1 : count + 1);
}
}
br.close();
}
} catch (NullPointerException | IOException e) {
e.printStackTrace();
System.out.println("Unable to read files: " + e);
}
}
}
//COMPUTING THE TOTAL NUMBER OF WORDS FROM ALL THE TEXT FILES COMBINED
System.out.println("THE TOTAL NUMBER OF WORDS IN COLLECTED CORPUS IS : \t" + wordCount + "\n");
for(int i = 0, size = allWords.size(); i < size; i++){
String distinctWord = allWords.get(i);
//adding a word into the 'distinctWords' list if it doesn't already occur
if(!distinctWords.contains(distinctWord)){
distinctWords.add(distinctWord);
}
}
//PRINTING THE DISTINCT WORDS
System.out.println("THE DISTINCT WORDS IN TOTAL ARE :\t " + distinctWords.size() + "\n");
System.out.println("PRINTING CONTENTS OF THE BIGRAMS HASHMAP... ");
System.out.println(bigramMap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
System.out.println("PRINTING CONTENTS OF THE TRIGRAMS HASHMAP... ");
System.out.println(hashmap);
System.out.println("================================================================================================================================================================================================================================================================================================================\n");
//QUITTING APPLICATION
String userInput = null;
while(true) {
System.out.println("\n**********************************************************************************************************************************************************************************************************************************");
System.out.println("\n\n\t\tPLEASE ENTER A WORD OR PHRASE YOU WOULD LIKE A PREDICTION OF THE NEXT WORD FROM:");
System.out.println("\t\t\t\t(OR TYPE IN 'Q' OR 'q' TO QUIT)");
userInput = input.nextLine();
if (userInput.equalsIgnoreCase("Q")) break;
//FORMAT USER INPUT
String[] users = userInput.toLowerCase().split("[?!,.\\s]+");
if (users.length < 2) {
userInput = users[0];
//System.out.println("\nENTRY '" + userInput + "' IS TOO SHORT TO PREDICT NEXT WORD. PLEASE ENTER 2 OR MORE WORDS");
//CALCULATING BIGRAM PROBABILITY
int sum = 0;
try {
for(String s : bigramMap.get(userInput).keySet()) {
sum += bigramMap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : bigramMap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(bigramMap.get(userInput).put(s, bigramMap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
} else {
userInput = users[users.length - 2] + " " + users[users.length - 1];
// System.out.println("FROM USER WE GET....");
// System.out.println(bigrams.get(userInput).keySet());
/* CALCULATING TRIGRAM PROBABILITY*/
int sum = 0;
try {
for(String s : hashmap.get(userInput).keySet()) {
sum += hashmap.get(userInput).get(s);
}
String stringHolder = null;
double numHolder = 0.0;
for(String s : hashmap.get(userInput).keySet()) {
//System.out.println("TWO");
double x = Math.round(hashmap.get(userInput).put(s, hashmap.get(userInput).get(s))/ (double)sum *100 );
if(s != null){
if(numHolder < x ){
stringHolder = s;
numHolder = x;
}
}
}
System.out.println("\nNEXT WORD PREDICTED IS '" + stringHolder + "'");
System.out.println("ITS PROBABILITY OF OCCURRENCE IS " + numHolder + "%");
} catch (Exception NullPointerException) {
System.out.println("\nSORRY. MATCH NOT FOUND.");
}
}
}
input.close();
}
}
My first Jframe which i would like to appear upon running the project has got a single textbox and a single button;
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String usersInput = jTextField1.getText();
Interface1 s = new Interface1();
s.setVisible(true);
dispose();
}
i would like for the user to enter data in the textbox and when they click on the button 'predict next word' then the output from the code execution is displayed on the second jframe which has got 3 labels and relative text areas.
NOTE; i couldn't paste the screenshots but if you run the NgramBetaE class you will get an idea of how the interfaces will be as i tried to explain them.
Thank you
Don't even try to link your GUI code to your NgramBetaE code as you've more work to do since the NgramBetaE is little more than one huge static main method that gets user input from the console with a Scanner and outputs to the console via printlns. Melding these two is like trying to put a square peg into a round hole.
Instead re-write the whole thing with an eye towards object-oriented coding, including creation of an OOP-compliant model class with instance fields and methods, and a single GUI that gets the input and displays it, that holds an instance of the model class and that calls instance methods on this instance.
Consider creating non-GUI classes and methods for --
Reading in data from your text files
Analyzing and hashing the data held in the text files including calculating word frequencies etc...
Returning needed data after analysis in whatever data form it may be needed.
A method for allowing input of a String/phrase for testing, with return its predicted probability
Then create GUI code for:
Getting selected text file from the user. A JFileChooser and supporting code works well here.
Button to start analysis
JTextField to allow entering of phrase
JTextArea or perhaps JTable to display results of analysis
Note that you should avoid having more than one JFrame in your GUI. For more on this, please have a look at The Use of Multiple JFrames, Good/Bad Practice?

importing a csv file into a java swing table

I have a csv file of all the stock quotes on in the nyse. first column is symbol second column is the name of the company.
I have a search box and table made in netbeans using the java swing library.
Right now when I enter the name in the box it is returning the correct amount of rows. So for instance if I search GOOG it will only return 2 rows (1 row for the GOOG symbol and one row for the name in the full company name). However the data within the rows is not the correct ones it is just printing the first row of the csv file over and over. here is the code that gets executed when clicking the search button:
package my.Stock;
import java.util.ArrayList;
import java.util.Scanner;
import java.io.BufferedReader;
import java.util.StringTokenizer;
import java.io.FileReader;
import java.io.*;
public class searchy {
public static void doSearch(String s){
javax.swing.JTable resTable = StockUI.stockUI.getResultTable();
javax.swing.table.DefaultTableModel dtm =
(javax.swing.table.DefaultTableModel) resTable.getModel();
while (dtm.getRowCount()> 0 ) dtm.removeRow(0);
String sym = s.trim().toUpperCase();
try {
//csv file containing data
String strFile = "companylist.csv";
//create BufferedReader to read csv file
BufferedReader br = new BufferedReader( new FileReader(strFile));
String strLine = "";
StringTokenizer st = null;
int lineNumber = 0, tokenNumber = 0;
//create arraylist
ArrayList<String> arrayList = new ArrayList<String>();
//read comma separated file line by line
while( (strLine = br.readLine()) != null){
lineNumber++;
//break comma separated line using ","
st = new StringTokenizer(strLine, ",");
while(st.hasMoreTokens()){
//display csv values
tokenNumber++;
arrayList.add(st.nextToken());
//System.out.println("Line # " + lineNumber + ": "+ st.nextToken() + " " + st.nextToken());
} //end small while
//reset token number
tokenNumber = 0;
} //end big while loop
//send csv to an array
Object[] elements = arrayList.toArray();
/*
for(int i=0; i < elements.length ; i++) {
System.out.println(elements[i]);
} */
Scanner input = new Scanner(System.in);
System.out.print("Enter Ticker symbol");
//String sym = input.next().toUpperCase(); //convert to uppercase to match csv
int j=0;
for(int i=0; i < elements.length ; i++) {
if (((String) elements[i]).contains(sym)){
//System.out.println(elements[i]);
dtm.addRow(elements);
j++;
if (j==25) break; //only show this many results
}
}
}
catch(Exception e){
System.out.println("Exception while reading csv file: " + e);
}
}
}
I understand why this is happening but I am not sure how to tell it to print the correct lines since I can't use dtm.addRow(elements[i]);
Any help is greatly appreciated.
Try CSVManager.
I collect csv data for stocks from Yahoo, and, oddly enough, every now and then they mess it up by using a company name with a comma in it, e.g., "Dolby, Inc.". Of course, that throws off the parsing of the CSV file. I don't know if this might be your problem.
John Doner
package recommendation.event.test;
import java.io.FileReader;
import com.csvreader.CsvReader;
public class ReadCSV {
public static void main (String [] args){
try {
CsvReader products = new CsvReader("resources/Event Recommendation Engine Challenge/data/test.csv");
products.readHeaders();
while (products.readRecord())
{
String user = products.get("user");
String event = products.get("event");
String invited = products.get("invited");
String timestamp = products.get("timestamp");
System.out.println(user + " : " + event+" : "+invited+" : "+timestamp);
}
products.close();
}catch (Exception e) {
// TODO: handle exception
}
}
}

Categories