0

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.

My new code

Joe K.
  • 65
  • 1
  • 7
  • Try to format your code properly, there is plenty of empty or strangely placed "{}" blocks. – Arnaud Dec 30 '15 at 09:21
  • the for block {} is not correct – jsfviky Dec 30 '15 at 09:23
  • @Joe K. , can you please edit the question and add the code as text. External images can be 'lost' :) – rjdkolb Dec 30 '15 at 10:02
  • Possible duplicate of [Java: Reading integers from a file into an array](http://stackoverflow.com/questions/303913/java-reading-integers-from-a-file-into-an-array) – Uma Kanth Dec 30 '15 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 array – Joe K. Dec 30 '15 at 10:24

3 Answers3

1

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]);}
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
  • I did i global,it compiles but i get run time error : java.lang.ArrayIndexOutOfBoundsException: 1 – Joe K. Dec 30 '15 at 09:24
  • 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. – cylon Dec 30 '15 at 09:28
  • @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. – Uma Kanth Dec 30 '15 at 09:33
1

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.

cylon
  • 735
  • 1
  • 11
  • 26
Damien Polegato
  • 508
  • 4
  • 13
0

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]);
            }
Uma Kanth
  • 5,659
  • 2
  • 20
  • 41
coldy
  • 2,115
  • 2
  • 17
  • 28