My array keeps on printing out zeroes and I don't know why

import java.util.Scanner;
import java.io.*;
public class practice3
{
  public static void main(String[] args) throws IOException
  {
  int[] array = new int [99];
  array = inputData();
    for(int i=0; i<array.length; i++)
      System.out.printf("%d",array[i]);
  }


    public static int[] inputData() throws IOException
    {
      final int MAX= 100;
      int[] nums = new int[MAX];
      int count = 0;
      Scanner kb = new Scanner(System.in);
      System.out.print("Enter input file name: ");
      String input = kb.nextLine();
      File file = new File(input);

      if(!file.exists())
        {
          System.out.println("The file entered is not found");
          System.exit(0);
        }
      Scanner inputFile = new Scanner(file);
        while(inputFile.hasNext() && count < nums.length)
        {
          nums[count] = inputFile.nextInt();
          count++;
        }
          inputFile.close();
          return nums;
    }
    public static void printArray(int[] array, int counter)
    {
      System.out.println("Original array: ");
      System.out.printf("%,12\n", array);
    }
  }

I don't know why these zeroes are printed after the array values I test from opening a file. I want to print the array itself and not the rest of the numbers. I tried messing with the MAX variable, but I dont know what to do.

Upvotes: 0

Views: 1062

Answers (2)

Ivanushka
Ivanushka

Reputation: 1

  1. Refactor arrays from int to Integer (0 -> null)
  2. Add this before printing, it'll remove nulls from Integer (not int) array. (if int there will be zeroProblem)

    int count = 0;
    
    for (Integer i : array) {
        if (i != null) {
            count++;
        }
    }
    
    Integer[] newArray = new Integer[count];
    
    int index = 0;
    
    for (Integer i : array) {
        if (i != null) {
            newArray[index++] = i;
        }
    }
    

Upvotes: 0

user7502825
user7502825

Reputation:

The for loop in you main() iterates over the length of the array, which is 100 elements. The elements that you did not overwrite default to 0.

To solve this, pass the array as an argument to your inputData() and have it return how many elements it put into the array like:

public static int inputData(int[] input) {
  // ...
  input[count] = whatever;
  // ...
  return count;
}

Upvotes: 1

Related Questions