It compiles but when it runs i get an exception error: (I am trying numbers from a file, get the sum and then average it) This is what I have so far:
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
public class Average{
public static void main(String[]args)
{
int count=0;
long sum=0;
Scanner in=null;
File F= new File("C:\\Users\\Owner\\Documents\\My Documents\\JAVA\\Lesson 13\\numbers.txt");
try{
in= new Scanner(F);
while (in.hasNext()){
String number = in.nextLine();
sum=sum + Long.parseLong(number);
count++;
}
} catch(IOException i){
System.out.println("Error: File does not exist");
}
}
}
//This is the exception error I get:
Exception in thread "main" java.lang.NumberFormatException: For input string: " 2"
at java.lang.NumberFormatException.forInput...
at java.lang.Long.parseLong(Long.java:403)
at java.lang.Long.parseLong(Long.java:java:...
at Average.
Java Question: Why the heck is this not working?
Yes there is a space before the 2 in the string...
quick hack fix would be to do this ...
replace
String number = in.nextLine();
with
String number = in.nextLine().trim();
Reply:Try
sum=sum + Long.parseLong(number.trim());
Reply:There's a space character before number 2, and it's getting in the way of converting it from string to a number. Check your numbers.txt, second line.
Try to trim the string first, before converting.
Good luck!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment