STUDY/Java
기초 문법 복습(6) (확장 for문, repeat문, 미로 게임)
개발하는 멍발자
2022. 4. 18. 15:22
repeat문
System.out.println("0".repeat(i)); // 반복할 문자와 반복 기준
public class MultiplyTable {
public static void main(String[] args) {
for (int i = 5; i >= 1 ; i--) {
for (int j = 0; j < i; j++) {
}
/*
for (int j = 0; j < i; j++) {
System.out.print("0");
}
System.out.println();
}
*/
//System.out.print("0".repeat(i));//
System.out.println("0".repeat(i));
}
}
}
//코드블럭
00000
0000
000
00
0
<미로 게임>
package jachap01;
import java.io.IOException;
public class Miro {
public static void main(String[] args) throws IOException {
record Position(int x, int y) {
}
int[][] map = {
{1, 1, 1, 1, 1, 1},
{1, 0, 1, 0, 0, 1},
{1, 0, 0, 0, 1, 1},
{1, 0, 1, 0, 0, 1},
{1, 1, 1, 1, 1, 1}
};
var current = new Position(1, 1);
var goal = new Position(4, 3);
for (; ; ) {
//미로 표시
for (int y = 0; y < map.length; y++) {
for (int x = 0; x < map[y].length; x++) {
if (x == current.x() && y == current.y()) {
System.out.print("o");
} else if (map[y][x] == 1) {
System.out.print("*");
} else {
System.out.print(".");
}
}
System.out.println();
}
//goal 결정
if (current.equals(goal)) {
System.out.println("GOAL!");
break;
}
//키 입력
int ch = System.in.read();
// 눌려진 방향 좌표 얻기
var next = switch (ch) {
case 'a' -> new Position(current.x() - 1, current.y());
case 'w' -> new Position(current.x(), current.y() - 1);
case 's' -> new Position(current.x() + 1, current.y());
case 'z' -> new Position(current.x(), current.y() + 1);
default -> current;
};
// 누른 방향이 통로라면 진행
}
}
}
//결과
****** // *는 벽이고 o가 현재 위치다.
*o*..*
*...**
*.*..*
******
<구문: 확장된 for문>
for (var 변수: 배열 및 List) {
반복하는 처리내용
}
<공통 패턴>
var result = 초기값;
for (var a: data) {
if(a.length() >=4 (임의 숫자)) {
결과에 새로운 결과 추가하는 처리;
}