Calculating the sum of values from a text file? - java

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.

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
}

how to get an output python from java input?

actually, i'm new in python. Here, i want to get an output from class of python. but here, i input String from java.
here's the java code:
String word;
Scanner in = new Scanner(System.in);
System.out.println("input: ");
word = in.nextLine();
TryinPythonToJavaAgain ie = new TryinPythonToJavaAgain();
ie.execfile("~\\hello.py");
PyInstance hello = ie.createClass("Hello", word);
hello.invoke("run");
python code:
class Hello:
def __init__(self, abc):
self.abc = abc
def run(self):
print(self.abc)
if i input : "hello"
i have an error like this:
input:
hello
Exception in thread "main" Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
Java Result: 1
and if i input >2 word (e.g "hello world"), i have an error like this:
input:
hello world
Exception in thread "main" SyntaxError: ("no viable alternative at input 'world'", ('', 1, 12, 'Hello(hello world)\n'))
Java Result: 1
what should i fix in this code? thanks
If the code in your createClass method looks anything like this ...
PyInstance createClass( final String className, final String opts )
{
return (PyInstance) this.interpreter.eval(className + "(" + opts + ")");
}
... then I think you need to add quotes round the opts variable. The code above is from here which works since "None" gets turned into this.interpreter.eval(className(None)) which is valid whereas yours becomes this.interpreter.eval(className(hello world)) which isn't.
I've not tried it, but this.interpreter.eval(className("hello world")) would seem more likely to work.

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.

JAVA : Reading txt and take elements with StringTokenizer

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+")

Parse a task list

A file contains the following:
HPWAMain.exe 3876 Console 1 8,112 K
hpqwmiex.exe 3900 Services 0 6,256 K
WmiPrvSE.exe 3924 Services 0 8,576 K
jusched.exe 3960 Console 1 5,128 K
DivXUpdate.exe 3044 Console 1 16,160 K
WiFiMsg.exe 3984 Console 1 6,404 K
HpqToaster.exe 2236 Console 1 7,188 K
wmpnscfg.exe 3784 Console 1 6,536 K
wmpnetwk.exe 3732 Services 0 11,196 K
skypePM.exe 2040 Console 1 25,960 K
I want to get the process ID of the skypePM.exe. How is this possible in Java?
Any help is appreciated.
Algorithm
Open the file.
In a loop, read a line of text.
If the line of text starts with skypePM.exe then extract the number.
Repeat looping until all lines have been read from the file.
Close the file.
Implementation
import java.io.*;
public class T {
public static void main( String args[] ) throws Exception {
BufferedReader br = new BufferedReader(
new InputStreamReader(
new FileInputStream( "tasklist.txt" ) ) );
String line;
while( (line = br.readLine()) != null ) {
if( line.startsWith( "skypePM.exe" ) ) {
line = line.substring( "skypePM.exe".length() );
int taskId = Integer.parseInt( (line.trim().split( " " ))[0] );
System.out.println( "Task Id: " + taskId );
}
}
br.close();
}
}
Alternate Implementation
If you have Cygwin and related tools installed, you could use:
cat tasklist.txt | grep skypePM.exe | awk '{ print $2; }'
To find the Process Id of the application SlypePM..
Open the file
now read lines one by one
find the line which contains SkypePM.exe in the beginning
In the line containing SkypePM.exe parse the line to read the numbers after the process name leaving the spaces.
You get process id of the process
It is all string operations.
Remember the format of the file should not change after you write the code.
If you really want to parse the output, you may need a different strategy. If your output file really is the result of a tasklist execution, then it should have some column headers at the top of it like:
Image Name PID Session Name Session# Mem Usage
========================= ======== ================ =========== ============
I would use these, in particular the set of equal signs with spaces, to break any subsequent strings using a fixed-width column strategy. This way, you could have more flexibility in parsing the output if needed (i.e. maybe someone is looking for java.exe or wjava.exe). Do keep in mind the last column may not be padded with spaces all the way to the end.
I will say, in the strictest sense, the existing answers should work for just getting the PID.
Implementation in Java is not a good way. Shell or other script languages may help you a lot. Anyway, JAWK is a implementation of awk in Java, I think it may help you.

Categories