2차원 배열 (23.06.03)

·2023년 6월 7일
0

Coding Test

목록 보기
17/39
post-thumbnail

💡 문제 1

String 2차원 배열 6행 6열을 만들고 행의 맨 위와 제일 앞 열은 각 인덱스를 저장하세요.
그리고 사용자에게 행과 열을 입력 받아 해당 좌표의 값을 “X”로 변환해 2차원 배열을 출력하세요.

	[실행 화면]
	행 인덱스 입력 : 4
	열 인덱스 입력 : 2
	  0 1 2 3 4
	0 
	1
	2
	3
	4     X

✏️ 풀이

	    Scanner sc = new Scanner(System.in);

	    String[][] arr = new String[6][6];
	            
	    System.out.print("행 인덱스 입력 : ");
	    int rowIndex = sc.nextInt();
	    sc.nextLine();
	    
	    System.out.print("열 인덱스 입력 : ");
	    int colIndex = sc.nextInt();
	    sc.nextLine();
	      
	    int num1 = 0;
	    int num2 = 0;
	      
	    for(int row = 0; row < arr.length; row++) {
	    	for (int col = 0; col < arr[row].length; col++) {
	    		if(row == 0 && col != 0) {
	    			arr[row][col] = num1++ + " ";
	    			
	            } else if(col == 0 && row != 0) {
	            	arr[row][col] = num2++ + " ";
	               
	            } else {
	            	arr[row][col] = "  ";
	            }
	    		
	            arr[rowIndex+1][colIndex+1] = "X";
	            
	            System.out.print(arr[row][col]);
	    	}
	    	
	         System.out.println();
	    }

💡 문제 2

실습 문제9와 내용은 같으나 행 입력 시 99가 입력되지 않으면 무한 반복이 되도록 구현하세요.

✏️ 풀이

	    Scanner sc = new Scanner(System.in);

	    String[][] arr = new String[6][6];

	    while(true) {
	    	
	    	System.out.print("행 인덱스 입력 : ");
	    	int rowIndex = sc.nextInt();
	    	sc.nextLine();

	    	if(rowIndex == 99) {
	    		System.out.println("\n프로그램 종료");
	    		break;
	    		
	    	} else {
	    		
	    		System.out.print("열 인덱스 입력 : ");
	    		int colIndex = sc.nextInt();
	    		sc.nextLine();
	    		
	    		int num1 = 0;
	    		int num2 = 0;
	    		
	    		for(int row = 0; row < arr.length; row++) {
	    			for (int col = 0; col < arr[row].length; col++) {
	    				if(row == 0 && col != 0) {
	    					arr[row][col] = num1++ + " ";
	    					
	    				} else if(col == 0 && row != 0) {
	    					arr[row][col] = num2++ + " ";
	    					
	    				} else {
	    					arr[row][col] = "  ";
	    				}
	    				
	    				arr[rowIndex+1][colIndex+1] = "X";
	    				
	    				System.out.print(arr[row][col]);
	    			}
	    			
	    			System.out.println();
	    		
	    		}	    			
	    	}
	    }
profile
풀스택 개발자 기록집 📁

0개의 댓글