JAVA : Reading txt and take elements with StringTokenizer - java

i got an error problem! I open my file i read a line and then i take information from the line with StringTokenizer
my code works with one line but when i am trying to read another i got an error any help ?
here is my code
try{
line = reader.readLine();
while(line!=null){
StringTokenizer st = new StringTokenizer(line,"\t");
timer=st.nextToken("\t");
int Itimer=Integer.parseInt(timer);
// System.out.println(Itimer);
what_to_do=st.nextToken("\t");
// System.out.print(what_to_do);
flightnumber=st.nextToken();
int Iflightnumber=Integer.parseInt(flightnumber);
// System.out.print(Iflightnumber);
departure=st.nextToken("\t");
// System.out.print(departure);
flighttime=st.nextToken("\t");
int Iflighttime=Integer.parseInt(flighttime);
// System.out.print(Iflighttime);
Key=new KeyFlight(Iflightnumber,Iflighttime);
flight=new Flight(Key,true);
if(what_to_do.equals("insert")){
// System.out.print("worked");
if(departure.equals("D")){
result=true;
}else{result=false;}
flight.setdeparture(result);//8a mporousa na kanw new flight alla gia e3ikonomisi to ekana me seter//
EV.insert(flight);
// System.out.println("worked again");
}else if(what_to_do.equals("cancel")){
EV.remove(Key);
}
else if(what_to_do.equals("update")){
EV.UpdateKey(flight, Key);
}
line=reader.readLine();
and these are the errors Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at java.util.StringTokenizer.nextToken(Unknown Source)
at FlightSchedule.loadandStoreFile(FlightSchedule.java:54)
at FlightSchedule.main(FlightSchedule.java:13)
i wrote instead of last reader.readLine(), line=null and it worked
Code is ok its a StringTokenizer problem
examble of my txt format: 0 insert 370 D 425

The problem could be, you are looking for tab "\t" on you're stringTokenizer and maybe the space between youre data is not a tab is just a white space, try better line.split("\s+")

Related

How do I fix a NumberFormatException (from text file input)?

I was wondering if I could have some help with this NumberFormatException with code using a text input.
The result should be it being able to run properly and be able to first put 50 strings into the hashTable and then remove 10 afterwards.
I have tried placing the removeLine.next() inside a String datatype and then placing the String back inside the Integer.parseInt which didn't work.
Here is the class:
import java.io.*;
import java.util.*;
public class hashTest {
public static void main(String args[]) throws FileNotFoundException {
HashTable hashTable = new HashTable();
Scanner insert = new Scanner(new File("data1.txt"));
while(insert.hasNext()) {
String line = insert.nextLine();
Scanner insertLine = new Scanner(line);
insertLine.next();
insertLine.next();
int index = Integer.parseInt(insertLine.next());
String data = insertLine.nextLine();
hashTable.put(index, data);
}
Scanner remove = new Scanner(new File("data2.txt"));
while(remove.hasNext()) {
String line = remove.nextLine();
Scanner removeLine = new Scanner(line);
removeLine.next();
removeLine.next();
int index = Integer.parseInt(removeLine.next());
hashTable.remove(index);
}
}
}
data1.txt :
003 : 68682774 MALIK TULLER
004 : 24248685 FRANCE COELLO
005 : 25428367 DUSTY BANNON
006 : 79430806 MELVINA CORNEJO
007 : 98698743 MALIA HOGSTRUM
008 : 20316453 TOMASA POWANDA
009 : 39977566 CHONG MCOWEN
010 : 86770985 DUSTY CONFER
011 : 92800393 LINNIE GILMAN
012 : 31850991 WANETA DEWEES
013 : 81528001 NEAL HOLSTEGE
014 : 46531276 BRADLY BOMBACI
data2.txt :
92800393 LINNIE GILMAN
86770985 DUSTY CONFER
31850991 WANETA DEWEES
46531276 BRADLY BOMBACI
25428367 DUSTY BANNON
68682774 MALIK TULLER
18088219 PENNY JOTBLAD
48235250 KENNITH GRASSMYER
20316453 TOMASA POWANDA
54920021 TYSON COLBETH
22806858 LAVERNE WOLNIK
32244214 SHEMEKA HALLOWAY
81528001 NEAL HOLSTEGE
24248685 FRANCE COELLO
23331143 JUSTIN ADKIN
79430806 MELVINA CORNEJO
59245514 LESLEE PHIFER
64357276 SCOT PARREIRA
50725704 GENARO QUIDER
52298576 AUDIE UNCAPHER
54657809 MARTY ENOCHS
54526749 TOBI HEATLEY
24903965 ALONSO GILSTAD
84936051 DEONNA STRAZZA
62522327 AHMAD THAYER
90572271 ELIJAH METEVIER
88999386 ISMAEL ELKAN
NumberFormatExceptions with Integer.parseInt() are most often caused by attempting to read something into an int that is not actually an int. Try printing each line as it is read in. If you have a line that is not purely an int (e.g., Hello123), you will get this exception with Integer.parseInt(). A cleaner debugging method (and better coding practice) would be to catch the exception and print the problematic line. You will probably see right away what's causing the issue. When reading text input from anywhere, it's never good to assume that the data is of the format you're expecting.
When your input contains data other than the int values you need, you can read each line's values into an array and extract the proper value(s). Here's an example of how you might extract the values from a single line in your second data file. Keep in mind that this still makes assumptions about the input format and therefore, is not completely fool-proof.
try {
// Split the line by whitespace, saving the values into an array
String[] singleLineVals = someLine.split("\\s+");
// Extract the first value
int firstValue = Integer.parseInt(singleLineVals[0]);
} catch (NumberFormatException nfe) {
// Handle the exception
}

Calculating the sum of values from a text file?

im trying to find the sum of the cost of all my books in my libary system from a file, could someone say where im going wrong atm. It would be great help
int sum = 0;
File Fileobject = new File ("E:\\text files for java\\BooksToImport.txt");
try {
Scanner fileReader = new Scanner (Fileobject);
// Read and display each line of the file
while(fileReader.hasNext())
{
sum+= fileReader.nextInt ( );
line = fileReader.nextLine();
System.out.println(line);
System.out.println(sum);
}
fileReader.close();
This is my data im reading:
The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752
OOP_programming - Graham_Winter - 32.50 – Oreilly - 0471974555
Harry_potter - Jk_Rowling - 10 - Bloomsbury- 9788700631625
This is the errors im getting:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at c3500948JavaProjectAssignement1.c3500948.main(c3500948.java:80)
Asumming your file has fixed format Text (no other words has - as seperator) and position for amount value here is something you can try:
text file :
book1- author1- 100 - press1- 978846521988752
book2 - author2 - 100 - press2 - 9788928465887521
book3 - author3 - 100 - press3 - 9784659219887521
book4 - author4 - 100 - press4 - 9788928465887521
book5 - author5 - 100 - press5 - 9784659219887521
book6 - author6- 100 - press 6- 9788984659887521
TestClass.java
import java.util.Scanner;
import java.io.*;
class TestClass
{
public static void main(String [] args) throws Exception
{
FileReader file = new FileReader("test.txt");
Scanner sc = new Scanner(file);
double sum = 0;
while(sc.hasNext())
{
String line = sc.nextLine();
// spit the line on - char
String [] data = line.split("-");
// Important : assuming price is always at index 2 parse and use value
sum = sum + Double.parseDouble(data[2].trim());
}
sc.close();
System.out.println("Sum is "+sum);
}
}
The first line of your file is:
The_Hunger_Games - Suzanne_Collins - 5 - Scholastic_Press - 9781921988752
The code
sum+= fileReader.nextInt ( );
expects a number thought.
Before calculating the sum you need to parse out the part of the line which is the number to be added to the sum.
Scanner.next*() reads a stream until the next delimiter (the default is defined in Character.isWhitespace). When you call nextInt() it reads the next delimiter and then attempts to parse it as an int, if it is not then you get an InputMixmatchException. You can define your own delimiter like this (using an escaped regegex for <space>-<space>):
new Scanner(input).useDelimiter("\\s-\\s");
Then you would need to call .next() to skip over the parts of each line that you aren't parsing.
Now that last line of your example shows a hyphen directly following the publisher (without space). This fix might require more work over more data (such as book titles with hyphens in them). Hopefully, this gets you unstuck.

Parsing a Tab Separated File

I'm attempting to TSV from IMDB:
$hutter Battle of the Sexes (2017) (as $hutter Boy) [Bobby Riggs Fan] <10>
NVTION: The Star Nation Rapumentary (2016) (as $hutter Boy) [Himself] <1>
Secret in Their Eyes (2015) (uncredited) [2002 Dodger Fan]
Steve Jobs (2015) (uncredited) [1988 Opera House Patron]
Straight Outta Compton (2015) (uncredited) [Club Patron/Dopeman]
$lim, Bee Moe Fatherhood 101 (2013) (as Brandon Moore) [Himself - President, Passages]
For Thy Love 2 (2009) [Thug 1]
Night of the Jackals (2009) (V) [Trooth]
"Idle Talk" (2013) (as Brandon Moore) [Himself]
"Idle Times" (2012) {(#1.1)} (as Brandon Moore) [Detective Ryan Turner]
As you can some lines start with a tab and some do not. I want a map with the actor's name as a key and a list of movies as the value. Between the actor's name is one or more tabs to until the movie listing.
My code:
while ((line = reader.readLine()) != null) {
Matcher matcher = headerPattern.matcher(line);
boolean headerMatchFound = matcher.matches();
if (headerMatchFound) {
Logger.getLogger(ActorListParser.class.getName()).log(Level.INFO, "Header for actor list found");
String newline;
reader.readLine();
while ((newline = reader.readLine()) != null) {
String[] fullLine = null;
String actor;
String title;
Pattern startsWithTab = Pattern.compile("^\t.*");
Matcher tab = startsWithTab.matcher(newline);
boolean tabStartMatcher = tab.matches();
if (!tabStartMatcher) {
fullLine = newline.split("\t.*");
System.out.println("Actor: " + fullLine[0] +
"Movie: " + fullLine[1]);
}//this line will have code to match lines that start with tabs.
}
}
}
The way I've done this only works for a few lines before I get and arrayoutofbounds exception. How can I parse the lines and split them into 2 strings at max if they have one or more tabs?
There are subtleties in parsing tab/comma-delimited data files having to do with quoting and escaping.
To save yourself a lot of work, frustration and headaches you really should consider using one of the existing CSV parsing libaries such as OpenCSV or Apache Commons CSV.
Posted as an answer instead of a comment because the OP has not stated a reason for reinventing the wheel and there are some tasks that really have been "solved" once and for all.

How can i avoid this format exception despite trim

EDIT : hidden character mess'd with my editor.
I want to read from my text file and add objects to an array from it. I'm getting a
NumberFormatException: For input string : "2".
If I remove the first line of the file, I get a format exception for input string "3".
What am I missing there ?
ArrayList<Personne> listp = new ArrayList<Personne>();
try {
FileReader file = new FileReader(personneFilePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
String[] attributes = line.split(",");
listp.add(new Personne(Integer.parseInt(attributes[0].trim()), attributes[1], attributes[2], Double.parseDouble(attributes[3]), attributes[4], attributes[5], attributes[6]));
}
file.close();
} catch (FileNotFoundException e) {
System.out.println("Erreur 1 : " + e.getMessage());
} catch (IOException e) {
System.out.println("Erreur 2 : " + e.getMessage());
}
Here is the content of the file i'm reading;
2, Claire, Chazal, 65.0 , rue de Rennes, Laval, 53000
3, Jacques, Dupont, 90.0 , rue des Anges, Paris, 75000
4, Celine, Dia, 66.0 , rue Diderot, Paris, 75000
5, Remy, Cheval, 88.0 , rue du paradis, Nantes, 44000
It loosk like your file contains some unprintable characters near 2 which is not whitespace so trim() can't remove it.
To remove it you can use replaceAll("\\D","") instead of trim().
Better preferred solution would be removing cause of this problem, so set up your editor/file format/encoding properly and stop placing these characters in your file.
What you are doing looks fine.
I would recommend using debug mode (IntelliJ or Eclipse work well for this) and stepping into the Integer.parseInt method to see what input it is getting or where it fails.
Alternatively, add a print statement to see the value of attributes[0].trim(), maybe also the length of the string. It seems like there may be a non-printable character.

Weird BufferedReader behavior for a huge file

I am getting a very weird error. So, my program read a csv file.
Whenever it comes to this line:
"275081";"cernusco astreet, milan, italy";NULL
I get an error:
In the debug screen, I see that the BufferedReader read only
"275081";"cernusco as
That is a part of the line. But, it should read all of the line.
What bugs me the most is when I simply remove that line out of the csv file, the bug disappear! The program runs without any problem. I can remove the line, maybe it is a bad input or whatever; but, I want to understand why I am having this problem.
For better understanding, I will include a part of my code here:
reader = new BufferedReader(new FileReader(userFile));
reader.readLine(); // skip first line
while ((line = reader.readLine()) != null) {
String[] fields = line.split("\";\"");
int id = Integer.parseInt(stripPunctionMark(fields[0]));
String location = fields[1];
if (location.contains("\";")) { // When there is no age. The data is represented as "location";NULL. We cannot split for ";" here. So check for "; and split.
location = location.split("\";")[0];
System.out.printf("Added %d at %s\n", id, location);
people.put(id, new Person(id, location));
numberOfPeople++;
}
else {
int age = Integer.parseInt(stripPunctionMark(fields[2]));
people.put(id, new Person(id, location, age));
System.out.printf("Added %d at: %s age: %d \n", id, location, age);
numberOfPeople++;
}
Also, you can find the csv file here or here is a short version of the part that I encountered the error:
"275078";"el paso, texas, usa";"62"
"275079";"istanbul, eurasia, turkey";"26"
"275080";"madrid, n/a, spain";"29"
"275081";"cernusco astreet, milan, italy";NULL
"275082";"hacienda heights, california, usa";"16"
"275083";"cedar rapids, iowa, usa";"22"
This has nothing whatsoever to do with BufferedReader. It doesn't even appear in the stack trace.
It has to do with your failure to check the result and length of the array returned by String.split(). Instead you are just assuming the input is well-formed, with at least three columns in each row, and you have no defences if it isn't.

Categories