I would like to know how to write the substitution and display of values in a two-dimensional array in a separate for statement.

Asked 2 months ago, Updated 2 months ago, 1 views

I'm currently studying two-dimensional arrays, and one of the problems was, "Create an array of double and set the value of element [x][y] to x*y (without initializer)."
So I was able to display them in one for statement, but then there was another for statement that said, "Let's substitute and display them in different for statements.
That's what I was thinking, but I can't display it well no matter how I try.

How can I change the display and substitution from the code below to another for statement?

double[][]s=new double[7][6];
    for(intx=1;x<s.length;x++){
        for(inty=1;y<s[x].length;y++){
            s[x][y]=x*y;
            System.out.println(s[x][y]);

        }
    }

I would appreciate it if you could let me know.
Thank you for your cooperation.

java

2022-09-30 11:03

3 Answers

If you simply want to divide it into different for statements, I think you should do the following.

for(intx=1;x<s.length;x++){
    for(inty=1;y<s[x].length;y++){
        s[x][y]=x*y;
    }
}
for(intx=1;x<s.length;x++){
     for(inty=1;y<s[x].length;y++){
         System.out.println(s[x][y]);
     }
}

If you do the following, the data may be a little easier to see.

// Import java.utils.Arrays at the beginning of the file
import java.util.Arrays;

for(intx=1;x<s.length;x++){
    for(inty=1;y<s[x].length;y++){
        s[x][y]=x*y;
    }
}
for (double[]data:s) {
     System.out.println (Arrays.toString(data));
}


2022-09-30 11:03

I don't understand the meaning of the question, but is it like this?
Replace (s=x*y) and display (System.out.println(s[x][y])) in separate for statements.

double[][]s=new double[7][6];

for(intx=0;x<s.length;x++){
    for(inty=0;y<s[x].length;y++){
        s=x*y;
    }
}

for(intx=0;x<s.length;x++){
    for(inty=0;y<s[x].length;y++){
        System.out.println(s[x][y]);
    }
}


2022-09-30 11:03

It doesn't directly concern the subject, so I thought I would leave a comment, but the evaluation was not enough, so I will write it here.

Perhaps, the subscripts of the array do not start from 1, but from zero.
As litmon wrote, the counter variable used in the for statement should start at zero.

Of course, depending on the language, there may be specifications that start with subscript 1.
In that case, I think the termination condition part of the for statement will be n<=length instead of n<length.

We recommend that you check what is inside the array, such as specifying an array with a maximum value subscript for the output function, specifying 0 or specifying 1.

Probably, but under the current state, I think the number 0 (equivalent to the first one) of the array is uninitialized.


2022-09-30 11:03

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.