3행 3열짜리 문자열 배열을 선언 및 할당하고 인덱스 0행 0열부터 2행 2열까지 차례대로 접근하여 “(0, 0)”과 같은 형식으로 저장 후 출력하세요.
(0, 0)(0, 1)(0, 2)
(1, 0)(1, 1)(1, 2)
(2, 0)(2, 1)(2, 2)
public class Main {
public static void main(String[] args) {
String[][] a = new String[3][3];
for( int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
System.out.print("(" + i + ", " + j + ")");
}System.out.println(" ");
}
}
}
4행 4열짜리 정수형 배열을 선언 및 할당하고
1) 1 ~ 16까지 값을 차례대로 저장하세요.
2) 저장된 값들을 차례대로 출력하세요.
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
public class Main {
public static void main(String[] args) {
int[][] a = new int[4][4];
int num = 0;
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
num += 1;
a[i][j] += num;
System.out.print(a[i][j] + " ");
}System.out.println(" ");
}
}
}
4행 4열짜리 정수형 배열을 선언 및 할당하고
1) 16 ~ 1과 같이 값을 거꾸로 저장하세요.
2) 저장된 값들을 차례대로 출력하세요.
16 15 14 13
12 11 10 9
8 7 6 5
4 3 2 1
public class Main {
public static void main(String[] args) {
int[][] a = new int[4][4];
int num = 1;
for(int i = 0; i < a.length; i++) {
for(int j = 0; j < a[i].length; j++) {
num--;
a[i][j] += num + (a.length*a[i].length);
System.out.print(a[i][j] + " ");
}System.out.println(" ");
}
}
}
4행 4열 2차원 배열을 생성하여 0행 0열부터 2행 2열까지는 1~10까지의 임의의 정수 값 저장 후 아래의 내용처럼 처리하세요.
9 3 7 19
3 6 9 18
6 10 10 26
18 19 26 63
int[][] arr = new int[4][4];
int rowFinal = arr.length - 1;
int colFinal = arr[0].length - 1;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
if (i != rowFinal && j != colFinal) {
arr[i][j] = (int)(Math.random() * 10);
arr[i][colFinal] += arr[i][j];
arr[rowFinal][i] += arr[i][j];
arr[rowFinal][colFinal] += arr[i][j];
}
System.out.printf("%2d ", arr[i][j]);
}
System.out.println();
}
2차원 배열의 행과 열의 크기를 사용자에게 직접 입력받되, 1~10사이 숫자가 아니면 “반드시 1~10 사이의 정수를 입력해야 합니다.” 출력 후 다시 정수를 받게 하세요. 크기가 정해진 이차원 배열 안에는 영어 대문자가 랜덤으로 들어가게 한 뒤 출력하세요. (char형은 숫자를 더해서 문자를 표현할 수 있고 65는 A를 나타냄, 알파벳은 총 26글자)
행 크기 : 5
열 크기 : 4
T P M B
U I H S
Q M B H
H B I X
G F X I
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int row = 0;
int col = 0;
int[][] arr;
int minValue = 1;
int maxValue = 10;
// 정수 1~10사이의 행의 크기를 입력받는다.
for(;;) {
System.out.print("행의 크기를 입력하세요. (정수 1~10사이의 수) : ");
row = sc.nextInt();
if( minValue > row || row > maxValue) {
System.out.println("반드시 1~10 사이의 정수를 입력해야 합니다.");
}else {
System.out.print("열의 크기를 입력하세요. (정수 1~10사이의 수) : ");
col = sc.nextInt();
if(minValue > col || col > maxValue) {
System.out.println("반드시 1~10 사이의 정수를 입력해야 합니다.");
}else {
arr = new int[row][col];
for(int i = 0; i < arr.length; i++) {
for(int j = 0; j <arr[i].length; j++) {
char ch = (char) ((Math.random() * 26) + 65);
arr[i][j] = ch;
System.out.print((char)arr[i][j] + " ");
}System.out.println("");
}
break;
}
}
}
}
}