1

I'm trying to convert command line arguments in an int array, but it appears a "0" in the end of the array. How can I fix it?

import java.util.Arrays;

public static void main(String[] args){
        int[] game = new int[9];
        for (int i = 0; i <= 8; i++)
        game[i] = Integer.parseInt(args[i]);
        System.out.println(Arrays.toString(game));
}

Example run:

$ java edu.kit.informatik.TicTacToe 5 6 4 1 2 3 7 8 9
[5, 6, 4, 1, 2, 3, 7, 8, 9, 0]
1
  • 1
    Is that really the output from that code? I don't see how a new int[9] array with 9 elements could be printed with 10 numbers in it. Commented Dec 15, 2020 at 17:47

2 Answers 2

1

I have tested your code, there aren't '0' at the end of the list. I recommend you that use args.length for handling variety arguments count.

    public static void main(String[] args) {
        int[] game = new int[args.length];
        for (int i = 0; i < args.length; i++)
            game[i] = Integer.parseInt(args[i]);
        System.out.println(Arrays.toString(game));
    }
Sign up to request clarification or add additional context in comments.

Comments

0

When you create a new int[] array in Java, its initial contents are all zeros. If you then fill it up with fewer numbers than it is long, you'll see the zeros that have not been overwritten at the end.

// creating an array of size 10
int[] array = new int[10];

// only filling up the first 8 elements
for (int i = 1; i <= 8; i++) {
    array[i-1] = i;
}

// printing the full array
for (int i = 0; i < array.length; i++) {
    System.out.print(i + " ");
}
System.out.println();

This will output:

1 2 3 4 5 6 7 8 0 0

The last two zeros are just the elements that have not been set to anything else.

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.