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

5
  • Try to format your code properly, there is plenty of empty or strangely placed "{}" blocks. Commented Dec 30, 2015 at 9:21
  • the for block {} is not correct Commented 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' :) Commented Dec 30, 2015 at 10:02
  • Possible duplicate of Java: Reading integers from a file into an array Commented 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 array Commented Dec 30, 2015 at 10:24

3 Answers 3

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]);}
Sign up to request clarification or add additional context in comments.

3 Comments

I did i global,it compiles but i get run time error : java.lang.ArrayIndexOutOfBoundsException: 1
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 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.
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.

1 Comment

@JoeK. You're mixing while loop with for loop. Which isn't necessary in this case. Use one loop.
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]);
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.