0

Hi, I'm a beginner with Java, can anyone tell me where my error is, I'm sure there's something I'm missing here with the array logic:

public void scalarMultiplication(int c) {
        for( int i=0; i <values.length - 1;i++){
            for(int j=0; j < values.length - 1;j++){
                values[i][j] = values[i][j] * c;
                }

main:

Matrix n = new Matrix(new int[][] { { 1, 0, -1 }, { 1, 3, 3 },
                { -2, -4, 1 }, { 0, 0, 1 } });
n.scalarMultiplication(-1);

my output:

[-1, 0, 1]
[-1, -3, -3]
[2, 4, -1]
[0, 0, 1]

*The lost row of the matrix is not multiplied by -1
Any suggestions would be appreciated.

2
Contributors
1
Reply
15
Views
3 Years
Discussion Span
Last Post by JamesCherrill
1

Those 2 code fragments don't quite add up, but...
you have a 2D array 4x3, so the array's length is 4
in your loops you use the length to control the loop for both indexes, so you will have a problem with the second index.

In Java it's misleading to think of 2D arrays at all. All Java arrays are one-dimensional, but each element may also be an array. Sub-arrays do not have to be the same size. It's perfectly valid to have a triangular array like {{1},{2,3},{4,5,6}}. So in general, the safe way to loop through an array of arrays looks like

int[][] array = ...
for (int i = 0; i < array.length; i++) {
   for (int j = 0; j < array[i].length; j++) {
      array[i][j] = ...

Edited by JamesCherrill

Votes + Comments
Thanks JamesCherrill
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.