So I want draw a field (of array strings) with obstacles and free spaces. "+"
are the obstacles and free spaces are just ""
. And if we have a free space, I want it replaced by "*"
. I will choose one specific element of that 2d array that equals ""
and that will be replaced by "1"
.
My question isn't as long as it seems, you could ignore the 2 codes below. Here is summary, if unclear, please read to the end:
Why aren't these things equal to each other?
if(field[i][j]==field[5][1]){
System.out.print("1");
}
and
if(i==5 && j==1){
System.out.print("1");
}
First code doesn't work. That specific array element here will be field[5][1]
which I want replace by 1
:
public class Test{
public static void main(String[] args){
String[][] field = {{"+" , "+" , "+" , "+" ,"+" , "+" , "+"},
{"+" , "+" , "+" , "+" ,"+" , "" , "+"},
{"+" , "+" , "+" , "+" ,"" , "" , "+"},
{"+" , "+" , "+" , "" ,"" , "+" , "+"},
{"+" , "" , "" , "" ,"+" , "+" , "+"},
{"+" , "" , "+" , "+" ,"+" , "+" , "+"},
{"+" , "+" , "+" , "+" ,"+" , "+" , "+"}};
int x = field.length;
for(int i=0; i<x; i++){
for(int j=0; j<field[i].length; j++){
System.out.print(field[i][j]);
if(field[i][j] != "+"){
if(field[i][j]==field[5][1]){
System.out.print("1");
}
else{
System.out.print("*");
}
}
}
System.out.println("");
}
}
}
Output:
+++++++
+++++1+
++++11+
+++11++
+111+++
+1+++++
+++++++
Second code works as desired:
public class Test{
public static void main(String[] args){
String[][] field = {{"+" , "+" , "+" , "+" ,"+" , "+" , "+"},
{"+" , "+" , "+" , "+" ,"+" , "" , "+"},
{"+" , "+" , "+" , "+" ,"" , "" , "+"},
{"+" , "+" , "+" , "" ,"" , "+" , "+"},
{"+" , "" , "" , "" ,"+" , "+" , "+"},
{"+" , "" , "+" , "+" ,"+" , "+" , "+"},
{"+" , "+" , "+" , "+" ,"+" , "+" , "+"}};
int x = field.length;
for(int i=0; i<x; i++){
for(int j=0; j<field[i].length; j++){
System.out.print(field[i][j]);
if(field[i][j] != "+"){
if(i==5 && j==1){
System.out.print("1");
}
else{
System.out.print("*");
}
}
}
System.out.println("");
}
}
}
Output:
+++++++
+++++*+
++++**+
+++**++
+***+++
+1+++++
+++++++