I am really new in java and I am trying to improve by exercising at home. I have this problem with my program, I can't save the int numbers from the txt file that I am reading in an array so I can work on it.
-
Try to format your code properly, there is plenty of empty or strangely placed "{}" blocks.Arnaud– Arnaud2015-12-30 09:21:53 +00:00Commented Dec 30, 2015 at 9:21
-
the for block {} is not correctjsfviky– jsfviky2015-12-30 09:23:28 +00:00Commented Dec 30, 2015 at 9:23
-
@Joe K. , can you please edit the question and add the code as text. External images can be 'lost' :)rjdkolb– rjdkolb2015-12-30 10:02:45 +00:00Commented Dec 30, 2015 at 10:02
-
Possible duplicate of Java: Reading integers from a file into an arrayUma Kanth– Uma Kanth2015-12-30 10:19:53 +00:00Commented Dec 30, 2015 at 10:19
-
I am not in that level to completely understand what null and the other codes i saw are ..I just want to know how to save the numbers of an txt.file in an arrayJoe K.– Joe K.2015-12-30 10:24:55 +00:00Commented Dec 30, 2015 at 10:24
Add a comment
|
3 Answers
i is out-of-scope in the print statement.
It will only be available in the for block. Whereas your print statement is outside the for loop.
It should be surrounded by a {} block to make it available for more than 1 statement.
for(int i =0; i < array.length; i++){
array[i] = in.nextInt();
System.out.println(array[i]);}
3 Comments
Joe K.
I did i global,it compiles but i get run time error : java.lang.ArrayIndexOutOfBoundsException: 1
cylon
You are assigning the first number to
num (length of the array), so your first line in .txt should be the number of the subsequent int's.Uma Kanth
@cylon True, But I didn't find a statement which calls
array[1], that's the reason I asked him to edit for the new code.You are doing:
int []array=new int[num];
which creates an array of length 1, since you do
num = in.nextInt();
You could for example use a List<Integer> intList = new ArrayList<Integer>() then you can add your ints to the list in your loop.
1 Comment
Uma Kanth
@JoeK. You're mixing while loop with for loop. Which isn't necessary in this case. Use one loop.
Use BufferReader to read the txt
BufferedReader br = new BufferedReader(new FileReader("/home/input.txt"));
Then all you need to do is iterate through using br.readLine() and assign it to an array as below:
while ((sCurrentLine = br.readLine()) != null) {
array[i]= Integer.parseInt(sCurrentLine);
i++;
}
for(int j=0;j<array.length;j++){
System.out.println(array[j]);
}