for(Type variable name: array){
}
I was wondering for a moment how to expand a two-dimensional array by combining the method of turning a loop while assigning the array on the right of: to the variable on the left, like PHP.
foreach($datas as $key => $value){
for($i = 0; $i < count($value); i++){
$value[i] = 0;
}
}
I thought of using foreach, but it seems that I have to create another object in java, so I wanted to do something about it.
public class Control {
public static void main(String[] args) {
int[][] datas = {
{0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,1,1,1,1,1,0},
{0,0,0,0,0,0,1,1,1,1,0},
{0,0,0,0,0,1,1,1,1,1,0},
{0,0,0,0,1,1,1,1,1,1,0},
{0,0,0,1,1,1,1,1,0,1,0},
{0,0,1,1,1,1,1,0,0,0,0},
{0,0,0,1,1,1,0,0,0,0,0},
{0,0,0,0,1,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0},
};
for(int[] data : datas ) {
for(int value : data) {
if(value == 0) {
System.out.print(" ");
} else {
System.out.print("* ");
}
}
System.out.println(""); //Line breaks after expanding the nested array
}
}
}
Execution result
* * * * *
* * * *
* * * * *
* * * * * *
* * * * * *
* * * * *
* * *
*
Recommended Posts