Reputation: 55
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.
Upvotes: 1
Views: 711
Reputation: 21004
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.
Upvotes: 2