Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Reading integers from a file into an array

Tags:

java

arrays

io

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.

like image 531
Northener Avatar asked Nov 20 '08 00:11

Northener


People also ask

How do you read a file and store it into an array in Java?

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.

Can we convert int to array in Java?

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.


2 Answers

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();
}
like image 86
Julien Grenier Avatar answered Sep 19 '22 13:09

Julien Grenier


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.)

like image 32
erickson Avatar answered Sep 17 '22 13:09

erickson