Error Parsing a Csv File with Java - java

I have a csv file with values like these:
1/1/1983;1,7;-3;8;-0,7;84;4;2;11;0;1030;0;0
2/1/1983;2,7;-2;8,4;1,9;94;2;2;15;0;1027;0;0
3/1/1983;4,1;-0,4;11,3;3,1;93;3;3;13;0;1030;0;0
4/1/1983;7,6;1,3;15;5,1;84;9;8;28;0;1027;0;0
5/1/1983;5,6;1,4;10;5,1;97;2;2;11;0;1023;0;0
6/1/1983;7;5,5;7,5;7;100;1;3;9;0;1028;0;0
7/1/1983;7,7;5;13,4;7,1;96;1;4;20;0;1029;0;0
8/1/1983;7,9;7;15,5;7,4;97;2;7;24;0;1029;0;1
9/1/1983;6,7;1;10,3;4,1;83;8;15;44;0;1033;0;0,3
10/1/1983;2,2;-1,9;8;0,4;88;8;4;13;0;1036;0;0
11/1/1983;0,7;-3,4;6,4;-1,2;87;3;1;13;0;1038;0;0
12/1/1983;0,2;-4,7;8;-1,7;87;6;4;9;0;1037;0;0
13/1/1983;1,7;-5,2;11,1;-0,1;88;4;3;15;0;1032;0;
So i have found on a website a Csv Parser implementation:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class ScannerExample
{
public static void main(String[] args) throws FileNotFoundException
{
//Array
ArrayList<String> weather = new ArrayList<String>();
//Get scanner instance
Scanner scanner = new Scanner(new File("C:/csv/meteo2.csv"));
//Set the delimiter used in file
scanner.useDelimiter(";");
//Get all tokens and store them in some data structure
//I am just printing them
while (scanner.hasNext())
{
weather.add(scanner.next());
}
System.out.println(weather.get(12));
//Do not forget to close the scanner
scanner.close();
}
}
But I Have a problem with the last element of one line and the first element of the successive line :
Infact when in the code i try to print the twelfth element (that must be 0). It prints
0
2/1/1983
But it's considered as only one element.
There is a solution to that?

If you want the semicolon and the linebreak as a delimiter, you should use
scanner.useDelimiter("[;\n]");
as Scanner#useDelimiter(String pattern) expects a regular expression as the parameter.

Related

Using Scanner to read file and store in ArrayList?

My Code so far. (Keep in mind this is my first programming class and While loops are still hard and new to me.
import java.util.ArrayList;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Group;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class InsultGenerator extends Application
{
ArrayList<String> adjectives1;
ArrayList<String> adjectives2;
ArrayList<String> nouns;
public void start(Stage primaryStage) throws FileNotFoundException
{
File file = new File("insultData.txt");
Scanner inFile = new Scanner(file);
while (inFile.hasNext())
{
}
}
}
So I have a project for my school that requires me to take a text file with 3 columns of text. I have to read the text file and store each column in 3 different ArrayLists. Here is the exact statement that described what is wanted.
Use a Scanner object to read the input file. Remember to add a throws FileNotFoundException clause to the start method header.
At the class level (so they can be used in other methods), declare and create three ArrayList objects called adjectives1, adjectives2, and nouns. All three lists should hold String objects.
When reading the input file, use a while loop to check to see if the input file still has data to read:
while (inFile.hasNext())
{
// read and store data
}
Each iteration of the while loop should read one line of data. Store the first adjective on the line in the adjectives1 list, the second in the adjectives2 list, and the noun in the nouns list. Use the next method of the Scanner to read each word. You may assume that each line will have all three values.
Note that you don't have to know how many lines of input data there will be. An ArrayList doesn't have a fixed capacity and expands and contracts as needed.
In the while loop, first read the next line of text to a String. Then, split the String into an array. Finally, push each element of the array to each array list.
String line = inFilw.nextLine();
String[] words = line.split(" ");
adjectives1.add(words[0]);
adjectives2.add(words[1]);
nouns.add(words[2]);

Java Using Scanner to Read File and Then Read Line

I'm trying to make a scanner that reads a file and deletes the spaces between each word. I can get this much but I can't get it to where they stay on the same line. I can't get the program to read a line, delete the spaces, and then go to the next line. This is the text from my practice project:
four score and
seven years ago our
fathers brought forth
on this continent
a new
nation
I'm currently only getting the first line
and this is my code:
import java.util.*;
import java.io.*;
public class CollapseSpace {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(fileInput.hasNext()){
nextLine = fileInput.nextLine();
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " "); // I tried to add a fileInput.NextLine() to consume the line but it isn't working properly
}
System.out.println();
}
}
}
If you only need to iterate line by line and remove spaces between words then you only need one loop, sample code below should do the trick
public static void main (String[] args) throws FileNotFoundException{
final Scanner fileInput = new Scanner(new File ("src/main/resources/textwithspaces.txt"));
while(fileInput.hasNext()){
final String nextLine = fileInput.nextLine();
// remove all spaces
final String lineWithOutSpaces = nextLine.replaceAll("\\s+","");
System.out.println(lineWithOutSpaces);
}
}
First of all, you shouldn't be using * to import classes. It is generally thought of as "bad practice" since it can interfere with your own classes, also it is not very explicit.
You need to loop the nextLine method inside your own loop. And also using a replaceAll method of the string would be good.
I have shown an example below:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
class Main {
public static void main(String[] args) throws FileNotFoundException {
// Create an object to represent a text file
File file = new File("textwithspaces.txt");
// Create a scanner with the text file as argument
Scanner scannerWithFile = new Scanner(file);
// Continue as long as it has a next line
do {
// Replace strings
String thisLine = scannerWithFile.nextLine();
// Only print the line out if not empty
if (!thisLine.isEmpty()) {
// Replace all spaces
thisLine = thisLine.replaceAll(" ", "");
// Print
System.out.println(thisLine);
}
} while (scannerWithFile.hasNext());
}
}
I also switched your while loop to a do while loop, this is so you can just instantly go into the loop without having to check for a condition first, it is done before next iteration.
Your biggest problem is that you declared nextLine = fileInput.nextLine(); outside of the loop, and then used that in Scanner lineInput = new Scanner(nextLine); so it becomes the first line of the text, but then never changes.
I also agree with the other comment that says you shouldn't be using *, it's considered bad practice to import broadly like that, as you're importing a whole lot of stuff you won't be using.
I reconstructed your code to make it work.
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Main {
public static void main (String[] args) throws FileNotFoundException{
Scanner fileInput = new Scanner(new File ("textwithspaces.txt"));
while(fileInput.hasNext()){
String nextLine = fileInput.nextLine();
Scanner lineInput = new Scanner(nextLine);
while(lineInput.hasNext()){
System.out.print(lineInput.next() + " ");
}
System.out.println();
}
}
}

Program terminates without printing anything

I am trying to print a line from the listed file, which contains a word stated. But the program does nothing. Can someone help me with the code? Thanks
import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
public class SearchingArrayLists {
public static void main(String[] args) throws Exception {
ArrayList names = new ArrayList();
Scanner scan = new Scanner(new File("random.txt"));
while (scan.hasNext()){
names.add(scan.next());
}
if (names.contains("legal")){
System.out.println(scan.next());
}
scan.close();
}
}
UPDATE:
Sorry, removed the loop. the file contains random text where the word "legal" is in there. the file was read by the scanner beforehand.
System.out.println(scan.next()); will throw an exception, since you are calling it after you consumed all the input in the while (scan.hasNext()) loop.
But it may not even reach that exception if your names list doesn't contain an exact match to the String "legal".
Scanner scan = new Scanner(new File("random.txt"));
String name = "" ;
while (scan.hasNextLine()){
name = scan.nextLine();
if (name.contains("legal")){
System.out.println(name);
}
}
scan.close();
Try above code , you even don't need list. I have not compiled it , so remove if any syntax error you got.

Storing file content into an array

I'm having a problem with my hangman program. I really think what I need to do is beyond what I understand about java. Here's my code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Random;
public class HangmanProject
{
public static void main(String[] args) throws FileNotFoundException
{
String scoreKeeper; // to keep track of score
int guessesLeft; // to keep track of guesses remaining
String[] wordList = new String[25];
final Random generator = new Random();
Scanner keyboard = new Scanner(System.in); // to read user's input
System.out.println("Welcome to Nick Carfagno's Hangman Project!");
// Create a scanner to read the secret words file
Scanner wordScan = null;
try
{
wordScan = new Scanner(new BufferedReader(new FileReader("words.txt")));
while (wordScan.hasNext())
{
}
}
finally
{
if (wordScan != null)
{
wordScan.close();
}
}
// get random word from array
class pickRand
{
public String get(String[] wordList)
{
int rnd = generator.nextInt(wordList.length);
return wordList[rnd];
}
}
System.out.println(wordList);
}
}
I was able to get the program to read a file and then print to screen, but I can't figure out how to store the words from file into an array. I not advanced at all, so please try and be as thorough as possible.
1) What you've got so far looks pretty good :)
2) Since you don't know exactly how many or few words you'll have, you don't want an "array". You're probably better off with an "ArrayList". Arrays are "fixed". Lists are "variable".
3) For each "word" you read, just ".add()" it to your arraylist
Voila! Done.
Here's a complete example:
http://www.daniweb.com/software-development/java/threads/311569/readingwriting-arraylist-fromto-file#
You need to save the read line in a String object and assign it to a certain field of the array. For example:
wordList[0] = myString;
This would assign the value of myString to the first field of your array.

Scanner Class hasNextLine infinite loop

why does this piece of code go into an infinite loop when I try to give it a basic text file?
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
public class TestFile
{
public static void main(String args[]) throws IOException
{
// Read in input file
File input = new File(args[0]);
Scanner freader = new Scanner(input);
while (freader.hasNextLine()) {
System.out.println("hi");
}
freader.close();
}
}
The print line just keeps going.
Because hasNexLine() does neither get the line nor change the state of the scanner. if it's true once, and no other methods of the scanner are called, it'll always be true.
Because you have to consume the nextLine so the code should be:
while ( theScanner.hasNextLine() ) {
String theLine = theScanner.nextLine();
}
If you don't invoke nextLine() you will always be watching at the same line and it will always answer true to that.
Add a call to nextLine or any other Scanner method that'll read in some input inside the while loop.
At the moment you're just repeatedly calling hasNextLine (which only returns a boolean, it doesn't modify the stream) without retrieving any input from freader, so if freader initially has another line within its input hasNextLine will always return true and your loop is essentially while (true).

Categories