1

Ok, so i want to create an integer matrix, say with 9 integers some positive and some negative like

int[][] myMatrix = {{1,5,-2},{7,9,3},{-4,-7,6}}

but i want to declare a String matrix of size 3 x 3. then Iterate through the integer matrix and if the current element has a positive integer put the word POSITIVE in the corresponding element in the String matrix, otherwise put NEGATIVE. my code prints fine when i run the matrix for integers but i'm confused how to write the condition for matrix. I already tried googling but nothing. here's my code:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;


public class 2D_Matrix {

public static void main(String[] args) throws IOException {


    int [][] firstMatrix = {{1, 5, -2},{7, 9, 3},{-4 , -7, 6}};
    String[][] secondMatrix = new String[3][3];


    for (int x = 0; x < 3; ++x) {
        for (int y = 0; y < 3; ++y) {               

    System.out.print(myMatrix[x][y] + "\t");

    }
        System.out.println();

    }
}

}

i tried many different combinations but nothing works or throws errors. for example:

if(x < 0){
System.out.print("Negative");
}
else if(y < 0){ 
System.out.print("Negative");
}
else
{System.out.print("positive");
}

but it throws error stating y cannot resolve to a variable. Any help would be much appreciated.

1
  • y has not been initialized Commented Apr 14, 2015 at 0:55

1 Answer 1

2

I think what you want is

for (int x = 0; x < 3; ++x) {
    for (int y = 0; y < 3; ++y) {

        if(firstMatrix[x][y] < 0)
            secondMatrix[x][y] = "NEGATIVE";
        else
            secondMatrix[x][y] = "POSITIVE";            
    }
 }

About your validations

if(x < 0){
}
else if(y < 0){ 
}
else
{
}

You were validating the index, but index of an array can't be negative. According to your request, you want to validate if the value is negative or positive. Refer to my snippet for how to retrieve value and validate them.

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

1 Comment

Thanks alot and you're absolutely correct. I wasn't thinking about index been negative

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.