I am new to programming and I am having some trouble taking a file with a list of numbers and converting it to an array of integers that I can then print in formatted columns (5 rows and 10 columns). I think I did the import correct using an ArrayList
but when I try to print the columns I run into issues. I think I need to use a for loop to get the columns to print but I'm not 100% sure. Any amount of help would be greatly appreciated! Here is my code:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Numbers {
private List < Integer > data = new ArrayList < Integer > (); //Create ArrayList
public static void main(String[] args) {
String filename = "C/Users/s/Desktop/file4/Input.txt";
Numbers rfe = new Numbers();
rfe.readFile(filename);
}
private void readFile(String name) {
String input;
try (BufferedReader reader = new BufferedReader(new FileReader(name))) {
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
int[] i = input;
for (i; i < null; i++) {
System.out.format("%20s, %10s", i);
}
}
} catch (FileNotFoundException fnfe) {
} catch (IOException ioe) {
} catch (Exception ex) { // Not required, but a good practice
ex.printStackTrace(); //Usually good for general handling
}
}
}
this is what the file contains (each number in a line):
32
73
63
47
72
34
26
84
27
75
95
10
48
88
28
65
71
40
14
11
67
76
77
80
12
15
30
74
13
41
21
22
57
17
99
92
52
38
18
46
62
64
39
16
43
29
79
49
19
60
You have two problems within your code. All of then at this portion:
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
int[] i = input;
for (i; i < null; i++) {
System.out.format("%20s, %10s", i);
}
}
First you did it right, you've added the readed number into your list: data.add(Integer.parseInt(input));
and this is all you need for this requirement add the number from the file to your list so you just need this for your while:
while ((input = reader.readLine()) != null) {
data.add(Integer.parseInt(input)); //Add each parsed number to the arraylist
}
After that you want to print it, the error you are seeing is because you are making a wrong assignment int[] i = input;
forget about this, you don't need it.
You need to loop through your list to print all the numbers
for (int i=0; i<data.size(); i++){
System.out.format("%20s, %10s", i); //here is your another problem
}
You want to print on that line two parameters "%20s, %10s"
but you only give one so either print only one or pass the i
twice:
System.out.format("%20s, %10s", i, i); //twice
Or
System.out.format("%10s", i); //just once