Read Tab Delimited file into ArrayList<ArrayList> in Java - java

I am looking for a way to read a tab delimited file of baseball stats into a two dimensional arraylist. I'm using a scanner to read the file, but I can't think of how to read just one line into an array list, stopping at the line break, then read the next line into the next arraylist.
This is my first time trying to create a multidimensional arraylist, and I thought it would be much the same as reading multidimensional arrays. I was clearly mistaken.
public static ArrayList dataRead(String fileloc) throws FileNotFoundException {
ArrayList array = new ArrayList<ArrayList>();
Scanner s = new Scanner(new File(fileloc)).useDelimiter("\t");
ArrayList<String> rows = new ArrayList<String>();
ArrayList cols = new ArrayList();
while(s.nextLine() != null) {
cols.add(s.next());
}
return array;
}
This is my code as of now. Would it be a better choice to read each line into a string, delimited by returns, then read each string into an appropriate arraylist?

You could use opencsv and set the delimeter to tab. Check out the examples on the link I provided.
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t');
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
Although it's not clear from your question what your actual issue is when trying to 'roll your own'

I'm not sure what the stats look like, but it might be better to use a HashMap which has Key/value pairs instead, but I could be wrong. I don't know what your dataset looks like.
For a start, you can delimit the lines by using the "\t" escape character.
For Example:
Scanner s = new Scanner(input).useDelimiter("\t");
Then you can loop through the results and for every pair add it to the map.

I think you need to rethink your data structure to something more conducive to what you are trying to store. I would recommend that you create a player object and store that into an arraylist.
public class Player{
double battavg;
String name;
//add more values like rbi, etc.
public Player(name,battavg){
this.name=name;
this.battavg=battavg;
}
public String getName(){
return name;
}
public String getBattAvg(){
return battavg;
}
public setBattAvg(double battavg){
this.battavg=battavg;
}
public setName(String name){
this.name=name;
}
}
public class baseball{
public static void main(String[] args){
ArrayList<Player> list = new ArrayList<Player>();
//read in values from csv
list.add(new Player(name,battavg));
}
}

Related

How to add column values to an array when reading a CSV in Java

I am trying to compare two different csv files, and I need each column saved into a different array to compare these values. My current code reads line by line, but I am not sure how to separate each line to get just a single cell value to add to an array (or arraylist). I have this code so far to read the CSV. I am using opencsv.
public static void main(String[] args) {
ArrayList<String> table = new ArrayList<String>();
try {
CSVReader reader = new CSVReader (new FileReader("src/A.csv"));
String [] nextline;
while ((nextline = reader.readNext()) != null) {
for(String token : nextline) {
//do something to add column value to array
}**

Using Java ArrayList with custom objects

I need to use ArrayLists to count the words in a text file and display their frequency. I would like to start by creating the ArrayList of "Word" objects. From that point I shouldn't have an issue. The problem I am encountering is when adding an object to the list. I receive an error stating "The method add(Word) in the type ArrayList is not applicable for the arguments (String)"
public ArrayList<Word> wordList = new ArrayList<Word>();
String fileName, word;
int counter;
Scanner reader = null;
Scanner scanner = new Scanner(System.in);
public void analyzeText() {
System.out.print("Please indicate the file that you would like to analyze (with the path included): ");
fileName = scanner.nextLine();
try {
reader = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException e) {
System.out.println("The file could not be found. The program will now exit.");
System.exit(0);
}
while (reader.hasNext()) {
word = reader.next().toLowerCase();
wordList.add(word);
counter++;
}
}
public class Word {
String value;
int frequency;
public Word(String v) {
value = v;
frequency = 1;
}
}
You need to add a Word Object not a String:
word = reader.next().toLowerCase();
Word myNewWord = new Word(word); /*Generates a Word Object using your constructor*/
wordList.add(myNewWord);
counter++
Hope that helps.
wordList is an array of "Word" objects. But in line 17
wordList.add(word);
you're adding another type of content into the array (a string).
Note there's an object-type, named "Word" (uppercase), and another variable named
"word" (lowercase) of type string.
You're adding a string "word" to the array list, but in this case you can add only objects "Word" to the ArrayList of name wordList.
You need to add Word object to your list. But you are assigning a string which is readed from scanner. You need to create a Word object.
I think, your solution for counting word is wrong. You are using wrong data structure. Hashmap fits better for this case. You can assign words as a key and count of words as a value.

Iterating in for-each loop Java

I have an ArrayList,where I search for needed element and then add the needed part of it to another ArrayList. The problem is that if I want to keep searching for the words,not only one word,I don't know how to keep going on the elements through the loop. With the using of iterator, I wouldn't be able to search for things I need.
public static ArrayList<String> FindWord(){
ArrayList<String> rewrite=new ArrayList<>();//
ArrayList<String> word=Reading();// rewrites the data from one string to other
String userinput=Chat();
for(String elmt:word){
if (elmt.contains(userinput) && elmt.contains("=")) {
String[] parts=elmt.split("\\=");
rewrite.add(parts[1]);
// here I must do something like word.next
}
}
System.out.println(rewrite);
return rewrite; // RETURNS THE SYNONIM OF THE WORD
}
So,it goes like if I input "hello", it will find me the word "greeting",which is a synonim in my text file. If I input "awesome", it will find the word "thanks", but if I input both of them it will input an empty array, like nothing is found instead of " greeting, thanks"
UPD:
The Reading() returns:
public static ArrayList<String> Reading() {
Scanner inputreader = null;
try {
inputreader = new Scanner(new FileInputStream("D:\\sinonims.txt"));
}catch (FileNotFoundException e1) { // OPENS FILE WITH SINONIMS
e1.printStackTrace();
System.out.println("File not found");
System.exit(0);
}
ArrayList<String> Sins=new ArrayList();
while(inputreader.hasNextLine()){
String l=inputreader.nextLine();
Sins.add(l); // REWRITES DATA FROM FILE TO ARRATLIST
}
inputreader.close();
System.out.print(Sins);
return Sins;
}
public static String Chat(){
System.out.println("Let's start talking.");
Scanner in=new Scanner(System.in);
String line=in.nextLine();
return line;
}
If you are trying to accept many inputs, you'll need to loop around the input & for loop.
The for loop already loops over all the words.
Note: I replaced contains for startsWith to prevent you catching the word on the other side of the equals
static ArrayList<String> word=Reading();
public static ArrayList<String> FindWord(){
ArrayList<String> rewrite=new ArrayList<>();
String userinput = "" ;
while (true) {
userinput=Chat();
if (userinput.equals("quit")) break;
for(String elmt:word){
if (elmt.startsWith(userinput) && elmt.contains("=")) {
String[] parts=elmt.split("\\=");
rewrite.add(parts[1]);
}
}
System.out.println(rewrite);
return rewrite; // RETURNS THE SYNONIM OF THE WORD
}
I can't really say this is the best way to approach your problem because it seems you need a Hashmap, not an Arraylist
contains fetches you exact match, split the text and match accordingly, store the results in new array list
you can create another arraylist and add your userinput values one by one into that list . you can iterate this newly created arraylist by using new for each loop on top of the current for each loop.
You should split the input string userinput with some specific delimiter.
Then for each word, Iterate through the splitted array and give each word as input , Find its Synonym with your technique and add it to the arraylist.
This can be implemented by doing some changes in your code.
public static ArrayList<String> FindWord()
{
ArrayList<String> rewrite=new ArrayList<>();
ArrayList<String> word=Reading();
String userinput=Chat();
String inputs[]=userinput.split(","); //Considering delimiter is comma(",") in user input
for(String input : inputs) //Giving each word as input at a time and search for it in word String
{
for(String elmt:word)
{
if (elmt.contains(input) && elmt.contains("="))
{
String[] parts=elmt.split("\\=");
rewrite.add(parts[1]);
}
}
}
System.out.println(rewrite);
return rewrite; // RETURNS THE SYNONIM OF THE WORD
}
So Here I am considering that the input is with delimiter Comma(",") so I have splitted input string with Comma(",") as you have given description in comments about your problem with space as delimiter.
When you will print the ArrayList, Automatically Output will be printed in separated manner with comma(, ).
So for Input : hello,awesome It will give output as greeting, thanks.

How to add elements from string added from console to a list in java

How I can add elements to a list from a input in java.
Like if i put:
Scanner reader = new Scanner("a,b,c,d,e);
I want to Have it like String[] a = {a,b,c,d,e];
Using any Scanner Methods with whiles , Really i am little bit lost
Sorry for my English( is not my main language)
If you know how many input items you are going to accept, declare an array before you start the input, then put each input into the array until you run out of array space.
The better way to do this is to use ArrayList:
ArrayList<String> inputList = new ArrayList<String>();
Using a Scanner, you can retrieve the next input (if you want an entire line, use reader.nextLine() to get that string. I'd suggest storing that in a local variable temporarily so you can examine it if you need to (you'll need some sort of termination sentinel or use hasNextLine() to see if there is more to read.
If you then need to return as an array, ArrayList has a toArray() method you can call.
To add inputs to list like this
import java.util.ArrayList;
import java.util.Scanner;
public class StackOverflow {
public static void main(String[] args) {
ArrayList<String> inputList = new ArrayList<String>();
Scanner reader = new Scanner(System.in);
String input = reader.nextLine();
inputList.add(input);
while (!input.equals("null")) {
input = reader.nextLine();
inputList.add(input);
}
}
}
This should work, the default token used by Scanner is whitespace characters.
public String[] getStringArray(String input, int arraySize) {
String[] stringArray = new String[arraySize];
Scanner s = new Scanner(input);
for (int i = 0; s.hasNext(); i++) {
stringArray[i] = s.next();
}
s.close();
return stringArray;
}

How do I create an iterator that will return only the elements that are different in Java?

More details of the issue:I need to create an iterator for a Stack of Strings that uses an ArrayList that returns only the words that are different after making the words all lowercase in the file and uses the Scanner for this. I must sort the array in the end. I have to create two separate classes for this problem.
This is what I have so far:
import java.io.*;
import java.util.*;
public class StackClass
{
static StringSet stringStack;
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
stringStack = new StringSet();
System.out.println("Please input the filename: ");
String fileName = console.next();
try {
FileReader file = new FileReader(fileName);
Scanner input = new Scanner(file);
while (input.hasNext())
{
input.useDelimiter("\\W");
//lcString.toLowerCase();
(I commented this out^ until I figure it out)
stringStack.add(input.next());
}
}
catch (FileNotFoundException e) {e.printStackTrace();}
}
}
And here is my other class:
import java.util.*;
public class StringSet implements Iterable<String>
{
static Stack<String> stringStack;
private ArrayList<String> stackList = new ArrayList<String>();
//for loop goes through all the words in stack
//if the word is found then ignore it, if not add it to the stack
public String add(String s)
{
for(int i=0;i>0;i++)
{
stringStack.push(s);
}
return s;
}
public int size( int i)
{
return stringStack.size();
}
public Iterator<String> iterator()
{return new WordIterator();}
class WordIterator implements Iterator<String>
{
private int i=0;
public boolean hasNext(){return i>0;}
public String next(){return stackList<String>;}
}
}
If the problem is "how to iterate only through unique words", I would simply use a HashSet for the words, and as you push words onto the stack
1) If the word is in the HashSet, don't push it on.
2) If the word is not in the HashSet, push it on and add it to the HashSet.
If you need to keep track of the number of occurrences, you can use a HashMap instead of a HashSet, where you increase the number of duplicate strings you encounter.
If you need to preserve the ordering & number of occurrences for something, I would keep a separate non-unique Stack where I'd just push everything.
I hope I understood your problem correctly.

Categories

Resources