Yousef Tamer
Yousef Tamer

Reputation: 1

extract integers from file and print it using array in Java

package foundations;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class gnfmd {
    public static void main(String[] args) throws IOException
    {
        int[] array = new int[40];
        int i = 0;
        File file = new File("hello.txt");
        if (file.exists())
        {
            Scanner hello = new Scanner(file);
            System.out.println("file found");


            while (hello.hasNext() && i < args.length)
            {
                array [i] = hello.nextInt();
                i++;
            }
            hello.close();
            
            for (int l : array)
            {
                System.out.println(array[l]);
            }
        }
        else
        {
            System.out.println("file not found");
        }

    }
}

zeros printed

I came across this problem during the java course. the exercise requires to extract all the integers from a .txt file and print them using arrays but it kept printing zeros even when I copy it from the model answer. can anyone please tell me where I have mistaken

Upvotes: 0

Views: 210

Answers (1)

JustAnotherDeveloper
JustAnotherDeveloper

Reputation: 2256

You are printing System.out.println(array[l]);. You should be printing System.out.println(l);, because l already holds a different integer from array on each iteration of the for (int l : array) loop. So on the first iteration, l will hold the value of array[0], on the second iteration it will hold array[1], etc. That and the fact that you only initialize the first args.length positions of the array are the reasons why it prints zeros, since the default values for all positions of an array of int are zeros, and you aren't assigning any other value to most, if not all, of those positions.

Example:

public class MyClass {
    public static void main(String args[]) {
      int[] array = {1,25,46,97};

      for (int i : array) {
          System.out.println(i);
      }
    }
}

Output:

1

25

46

97

Upvotes: 1

Related Questions