File fil = new File("Tall.txt");
FileReader inputFil = new FileReader(fil);
BufferedReader in = new BufferedReader(inputFil);
int [] tall = new int [100];
String s =in.readLine();
while(s!=null)
{
int i = 0;
tall[i] = Integer.parseInt(s); //this is line 19
System.out.println(tall[i]);
s = in.readLine();
}
in.close();
I am trying to use the file "Tall.txt" to write the integers contained in them into the array named "tall". It does this to some extent, but also when I run it, it throws the following exception (:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at BinarySok.main(BinarySok.java:19)
Why exactly does it do this, and how do I remove it? As I see it, I read the file as strings, and then convert it to ints, which isn't illegal.
In Java, we can store the content of the file into an array either by reading the file using a scanner or bufferedReader or FileReader or by using readAllLines method.
Just use % 10 to get the last digit and then divide your int by 10 to get to the next one. int temp = test; ArrayList<Integer> array = new ArrayList<Integer>(); do{ array. add(temp % 10); temp /= 10; } while (temp > 0); This will leave you with ArrayList containing your digits in reverse order.
You might want to do something like this (if you're in java 5 & up)
Scanner scanner = new Scanner(new File("tall.txt"));
int [] tall = new int [100];
int i = 0;
while(scanner.hasNextInt()){
tall[i++] = scanner.nextInt();
}
You must have an empty line in your file.
You may want to wrap your parseInt calls in a "try" block:
try {
tall[i++] = Integer.parseInt(s);
}
catch (NumberFormatException ex) {
continue;
}
Or simply check for empty strings before parsing:
if (s.length() == 0)
continue;
Note that by initializing your index variable i
inside the loop, it is always 0. You should move the declaration before the while
loop. (Or make it part of a for
loop.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With