0
Scanner input = new Scanner(System.in);
    System.out.println("What dimensions do you need");
    int z = input.nextInt();
    int y = input.nextInt();
    int[][] x = new int[z][y];
    for (int i = 0; i <= z; i++) {
        for (int j = 0; j <= y; j++) {
            System.out.println("What number do you want in " + i + " , "
                    + j);
            x[i][j] = input.nextInt();

        }
    }

After i reach a specific dimension, the program stops. if i enter the dimensions (1,1), it won't let me add values to (1,1); i can only input values for 0,0 and 0,1. How can i solve this?

5

4 Answers 4

3

Arrays start at 0. You need less than, not less than equal. Change

for (int i = 0; i <= z; i++) {
    for (int j = 0; j <= y; j++) {

to

for (int i = 0; i < z; i++) {
    for (int j = 0; j < y; j++) {

and dimensions 1,1 would be space for a single array of length 1 containing an array of length 1. Increase the size of any dimension to add more than one value.

Sign up to request clarification or add additional context in comments.

Comments

0

It's because you alloced less memory for your array.

Comments

0

Look at your for loops:

for (int i = 0; i <= z; i++) {
        for (int j = 0; j <= y; j++) {

It should be

for (int i = 0; i < z; i++) {
        for (int j = 0; j < y; j++) {

Comments

0

Arrays in most programming languages have 0 based indices.

This means that a int[+ a = new int[2] has two elements at index 0 and 1. So a[0] is a valid index, a[1] is valid too but a[2] is not. In addition this means that when you iterate over an array you don't need to use <= but < as condition on the index, because, for example

for (int i = 0; i <= 3; ++i)

will iterate for values of i = 0, 1, 2, 3, but 3 is an invalid index in a new int[3], so you need to do for (int i = 0; i < 3; ++i).

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.