How to add only unique values from CSV into ComboBox? - java

I want to read a csv File and put words " Jakarta " and " Bandung " in a combobox. Here's the input
id,from,
1,Jakarta
2,Jakarta
5,Jakarta
6,Jakarta
10,Bandung
11,Bandung
12,Bandung
I managed to get the words and put it in the combobox, but as you can see, the text file itself contains a lot word " Jakarta " and " Bandung " while i want to show both only once in the combobox.
Here's my temporary code, which works for now but inefficient and probably can't be used if the word has more variety
public String location;
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String csvFile = "C:\\Users\\USER\\Desktop\\Project Data.csv";
BufferedReader br = null;
LineNumberReader reader = null;
String line = "";
String cvsSplitBy = "-|\\,";
br = new BufferedReader(new FileReader(csvFile));
reader = new LineNumberReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
cmb1.addItem(location);
for(int i = 1; i < size; i++){
if(model.getElementAt(i).equals("from")){
cmb1.removeItemAt(i);
}
else if(model.getElementAt(i).equals("Bandung")){
cmb1.removeItemAt(i);
}
for(int j = 2; j < i; j++){
if(model.getElementAt(j).equals("Jakarta")){
cmb1.removeItemAt(j);
}
}
}
}
}
Someone else recommended this approach
boolean isEquals = false;
for(i = 0; i < a && !isEquals; i++){
isEquals = location.equals("Jakarta");
if(isEquals){
cmb1.addItem("Jakarta");
}
}
This code doesn't work. As the code doesn't stop once it adds a " Jakarta " but it stops after it completed a loop. thus it still creates duplicate within the combobox.
I would like to know if there's any other code i can try. Thank you

Try putting all the words in a Set first and then add it in the combobox. Set itself will take care of exact one occurrence of each word.
Something like this:
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bookingdata = line.split(cvsSplitBy);
location = bookingdata[1];
ComboBoxModel model = cmb1.getModel();
int size = model.getSize();
// add all location in set and set will only allow distinct values
locationSet.add(location);
}
// after looping through all location put it in combobox
for(String location:locationSet)cmb1.addItem(location);
}
}
As discussed in comments, Sets are meant to keep unique values. Please find the screenshot of JShell below:
PS: This is just to give an idea and may need some amendment as per requirement.
--EDITED--
As discussed, it seems you are still missing something, I tried and write below piece of code and worked fine
package com.digital.core;
import java.util.HashSet;
import java.util.Set;
import javax.swing.JComboBox;
import javax.swing.JFrame;
public class Test {
public static void main(String[] args) {
JFrame jframe = new JFrame();
jframe.setSize(300, 300);
String data = "id,from,\n" +
"1,Jakarta\n" +
"2,Jakarta\n" +
"5,Jakarta\n" +
"6,Jakarta\n" +
"10,Bandung\n" +
"11,Bandung\n" +
"12,Bandung";
String[] dataArr = data.split("\n");
Set<String> locationSet = new HashSet<>();
for(String line:dataArr) {
locationSet.add(line.split(",")[1]);
}
JComboBox<String> comboBox = new JComboBox<>();
for(String location:locationSet)
comboBox.addItem(location);
jframe.add(comboBox);
jframe.setVisible(true);
}
}

You could create an ObservablArrayList of strings and as you read the CSV file, check if the list already contains that string:
ObservableList<String> locationsList = FXCollections.observableArrayList();
// Add your strings to the array as they're loaded, but check to
// make sure the string does not already exist
if (!locationsList.contains(location)) {
locationsList.add(location);
}
Then, after reading the whole file and populating the list, just set the items in your combobox to that ObservableArrayList.

Related

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.

Trying to split array list of strings get warning #NonNull String regex Android Studio Java

I am trying to load a file from a previously saved values from an editText. On the next load I am trying to make the fields populated with the previously entered data using split to get everything on that line after the split, as seen in this picture. For some reason every time I try and split with .split("Name") everything between the quotation marks goes black instead of green and I get that #NonNull.
public void loadList(){
loadText = new ArrayList<String>();
Context context = getApplicationContext();
File file = new File (path + "/personalProfile.txt");
try{
editText_name.setText("");
editText_dob.setText("");
editText_mobile.setText("");
editText_journal.setText("");
editText_medical.setText("");
String line = "";
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
while((line = reader.readLine()) != null)
{
loadText.add(line);
}public void loadList(){
String loadedText = String.valueOf(loadText.get(0));
String rname = "Hello: Name";
String helloName [] = rname.split("Hello: ");
//String nameToText [] = loadedText.split("");
for(int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(0).split("Name:")));
}
//set all the editText values accordingly
}catch (Exception e){
System.out.println("Error " + e);
}
}
There is no string you have entered that would satisfy "Name: " in
"Hello: Name"
And I think what you want in your for loop is not element 0 all the time for your arraylist, it should be:
for (int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(i).split("Hello: ")));
}
But the more correct way would be:
for (int i = 0; i < loadText.size(); i++){
editText_name.setText(String.valueOf(loadText.get(i).replace("Hello: ")));
}
If you just wanted the name.
However I think the problem with not retrieving the values is you have to add:
#Override
public void onSaveInstanceState(Bundle out) {
out.putStringArrayList("loadValues", loadValues);
}
and to retrieve them:
#Override
public void onRestoreInstanceState(Bundle in) {
loadValues = in.getStringArrayList("loadValues");
//call method to set values again
}

Calculating the frequency of strings as they get stored in a nested hashmap

i want to write a code that stores strings in a hashmap as they are read from text files.
i have written the code below and it works, no errors, the frequency of every occurrence of the string combination does not change, it is always 1.
i am asking for assistance on how i can ensure that if a string combination appears more than once in the text file then its frequency should also increase.
this is my code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class NgramBetaC {
static String[] hashmapWord = null;
public static Map<String,Map<String, Integer>> bigrams = new HashMap<>();
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("Corpus4");
File[] listOfFiles = directory.listFiles();//To read from all listed iles in the "directory"
//String bWord[] = null;
int lineNumber = 0;
String line;
String files;
String delimiters = "[\\s+,?!:;.]";
int wordTracker = 0;
//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);
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 readBigrams = read + " " + read1;
final Integer count = null;
//bigrams.put(readBigrams, new HashMap() {{ put (read2, (count == null)? 1 : count + 1);}});
bigrams.put(readBigrams, new HashMap<String, Integer>());
bigrams.get(readBigrams).put(read2, (count == null) ? 1 : count+1);
} br.close();
}
}
} catch (NullPointerException | IOException e) {
e.printStackTrace();
System.out.println("Unable to read files: " + e);
}
}
}
}
THE LINES CONTAINED IN THE TEXT FILES ARE::
1.i would like some ice cream.
2.i would like to be in dubai this december.
3.i love to eat pasta.
4.i love to prepare pasta myself.
5.who will be coming to see me today?
THE OUTPUT I GET WHEN PRINTING CONTENTS OF THE HASHMAP IS:
{coming to={see=1}, would like={to=1}, in dubai={this=1}, prepare pasta={myself=1}, to eat={pasta=1}, like to={be=1}, to prepare={pasta=1}, will be={coming=1}, love to={prepare=1}, some ice={cream=1}, be in={dubai=1}, be coming={to=1}, dubai this={december=1}, to be={in=1}, i love={to=1}, to see={me=1}, who will={be=1}, like some={ice=1}, i would={like=1}, see me={today=1}}
Please assist! some string combinations are not even appearing.
THE OUTPUT I EXPECT AS I READ FROM THE FILES IS:
{coming to={see=1}, would like={to=1}, in dubai={this=1}, prepare pasta={myself=1}, to eat={pasta=1}, like to={be=1}, to prepare={pasta=1}, will be={coming=1}, love to={prepare=1}, some ice={cream=1}, be in={dubai=1}, be coming={to=1}, dubai this={december=1}, to be={in=1}, i love={to=1}, to see={me=1}, who will={be=1}, like some={ice=1}, i would={like=2}, see me={today=1}, love to {eat=1}, would like {some=1}, i would {love=1}, would love {to=1}}
Tentatively update the current structure without overwriting the originl content
Replace
bigrams.put(readBigrams, new HashMap<String, Integer>());
bigrams.get(readBigrams).put(read2, (count == null) ? 1 : count+1);
With
HashMap<String, Integer> counter = bigrams.get(readBigrams);
if (null == counter) {
counter = new HashMap<String, Integer>();
bigrams.put(readBigrams, counter);
}
Integer count = counter.get(read2);
counter.put(read2, count == null ? 1 : count + 1);

JAVA read text files, count numbers and write it to Jtable [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I am still learning JAVA and have been trying to find a solution for my program for a few days, but I haven't gotten it fixed yet.
I have many text files (my program saves). The files look like this:
text (tab) number (tab) number (tab)...
text (tab) number (tab) number (tab)...
(tab) means that there is tabulation mark,
text means that is text (string),
number means that there is number (integer).
number of files can be from 1 up to 32 and file with names like: january1; january2; january3...
I need to read all of those files (ignore strings) and sum only numbers like so:
while ((line = br.readLine()) != null) {
counter=counter+1;
String[] info = line.split("\\s+");
for(int j = 2; j < 8; j++) {
int num = Integer.parseInt(info[j]);
data[j][counter]=data[j][counter]+num;
}
};
Simply I want sum all that "tables" to array of arrays (or to any similar kind of variable) and then display it as table. If someone knows any solution or can link any similar calculation, that would be awesome!
So, as I see it, you have four questions you need answered, this goes against the site etiquette of asking A question, but will give it a shot
How to list a series of files, presumably using some kind of filter
How to read a file and process the data in some meaningful way
How to manage the data in data structure
Show the data in a JTable.
Listing files
Probably the simplest way to list files is to use File#list and pass a FileFilter which meets your needs
File[] files = new File(".").listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().toLowerCase().startsWith("janurary");
}
});
Now, I'd write a method which took a File object representing the directory you want to list and a FileFilter to use to search it...
public File[] listFiles(File dir, FileFilter filter) throws IOException {
if (dir.exists()) {
if (dir.isDirectory()) {
return dir.listFiles(filter);
} else {
throw new IOException(dir + " is not a valid directory");
}
} else {
throw new IOException(dir + " does not exist");
}
}
This way you could search for a number of different set of files based on different FileFilters.
Of course, you could also use the newer Paths/Files API to find files as well
Reading files...
Reading multiple files comes down to the same thing, reading a single file...
// BufferedReader has a nice readline method which makes
// it easier to read text with. You could use a Scanner
// but I prefer BufferedReader, but that's me...
try (BufferedReader br = new BufferedReader(new FileReader(new File("...")))) {
String line = null;
// Read each line
while ((line = br.readLine()) != null) {
// Split the line into individual parts, on the <tab> character
String parts[] = line.split("\t");
int sum = 0;
// Staring from the first number, sum the line...
for (int index = 1; index < parts.length; index++) {
sum += Integer.parseInt(parts[index].trim());
}
// Store the key/value pairs together some how
}
}
Now, we need some way to store the results of the calculations...
Have a look at Basic I/O for more details
Managing the data
Now, there are any number of ways you could do this, but since the amount of data is variable, you want a data structure that can grow dynamically.
My first thought would be to use a Map, but this assumes you want to combining rows with the same name, otherwise you should just us a List within a List, where the outer List represents the rows and the Inner list represents the column values...
Map<String, Integer> data = new HashMap<>(25);
File[] files = listFiles(someDir, januraryFilter);
for (File file : files {
readFile(file, data);
}
Where readFile is basically the code from before
protected void readData(File file, Map<String, Integer> data) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = null;
// Read each line
while ((line = br.readLine()) != null) {
//...
// Store the key/value pairs together some how
String name = parts[0];
if (data.containsKey(name)) {
int previous = data.get(name);
sum += previous;
}
data.put(name, sum);
}
}
}
Have a look at the Collections Trail for more details
Showing the data
And finally, we need to show the data. You could simply use a DefaultTableModel, but you already have the data in structure, why not re-use it with a custom TableModel
public class SummaryTableModel extends AbstractTableModel {
private Map<String, Integer> data;
private List<String> keyMap;
public SummaryTableModel(Map<String, Integer> data) {
this.data = new HashMap<>(data);
keyMap = new ArrayList<>(data.keySet());
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return 2;
}
#Override
public Class<?> getColumnClass(int columnIndex) {
Class type = Object.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
}
return type;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
Object value = null;
switch (columnIndex) {
case 0:
value = keyMap.get(rowIndex);
break;
case 1:
String key = keyMap.get(rowIndex);
value = data.get(key);
break;
}
return value;
}
}
Then you would simply apply it to a JTable...
add(new JScrollPane(new JTable(new SummaryTableModel(data)));
Take a look at How to Use Tables for more details
Conclusion
There are a lot of assumptions that have to be made which are missing from the context of the question; does the order of the files matter? Do you care about duplicate entries?
So it becomes near impossible to provide a single "answer" which will solve all of your problems
I took all the january1 january2... files from the location and used your same function to calculate the value to be stored.
Then I created a table with two headers, Day and Number. Then just added rows according to the values generated.
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
String line;
model.addColumn("Day");
model.addColumn("Number");
BufferedReader br = null;
model.addRow(new Object[]{"a","b"});
for(int i = 1; i < 32; i++)
{
try {
String sCurrentLine;
String filename = "january"+i;
br = new BufferedReader(new FileReader("C:\\january"+i+".txt"));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null) {
counter=counter+1;
String[] info = sCurrentLine.split("\\s+");
int sum = 0;
for(int j = 2; j < 8; j++) {
int num = Integer.parseInt(info[j]);
sum += num;
}
model.addRow(new Object[]{filename, sum+""});
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
JFrame f = new JFrame();
f.setSize(300, 300);
f.add(new JScrollPane(table));
f.setVisible(true);
Use Labled Loop and Try-Catch. Below piece adds all number in a line.
You could get some hint from here:
String line = "text 1 2 3 4 del";
String splitLine[] = line.split("\t");
int sumLine = 0;
int i = 0;
contSum: for (; i < splitLine.length; i++) {
try {
sumLine += Integer.parseInt(splitLine[i]);
} catch (Exception e) {
continue contSum;
}
}
System.out.println(sumLine);
Here is another example using vectors . in this example directories will be searched for ".txt" files and added to the JTable.
The doIt method will take in the folder where your text files are located.
this will then with recursion, look for files in folders.
each file found will be split and added following you example file.
public class FileFolderReader
{
private Vector<Vector> rows = new Vector<Vector>();
public static void main(String[] args)
{
FileFolderReader fileFolderReader = new FileFolderReader();
fileFolderReader.doIt("D:\\folderoffiles");
}
private void doIt(String path)
{
System.out.println(findFile(new File(path)) + " in total");
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Vector<String> columnNames = new Vector<String>();
columnNames.addElement("File Name");
columnNames.addElement("Size");
JTable table = new JTable(rows, columnNames);
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
private int findFile(File file)
{
int totalPerFile = 0;
int total = 0;
File[] list = file.listFiles(new FilenameFilter()
{
public boolean accept(File dir, String fileName)
{
return fileName.endsWith(".txt");
}
});
if (list != null)
for (File textFile : list)
{
if (textFile.isDirectory())
{
total = findFile(textFile);
}
else
{
totalPerFile = scanFile(textFile);
System.out.println(totalPerFile + " in " + textFile.getName());
Vector<String> rowItem = new Vector<String>();
rowItem.addElement(textFile.getName());
rowItem.addElement(Integer.toString(totalPerFile));
rows.addElement(rowItem);
total = total + totalPerFile;
}
}
return total;
}
public int scanFile(File file)
{
int sum = 0;
Scanner scanner = null;
try
{
scanner = new Scanner(file);
while (scanner.hasNextLine())
{
String line = scanner.nextLine();
String[] info = line.split("\\s+");
int count = 1;
for (String stingInt : info)
{
if (count != 1)
{
sum = sum + Integer.parseInt(stingInt);
}
count++;
}
}
scanner.close();
}
catch (FileNotFoundException e)
{
// you will need to handle this
// don't do this !
e.printStackTrace();
}
return sum;
}
}

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