int[]arr = { 10, 20, 30, 40, 50 };
int sum = 0;
for(int i=0; i<arr.length; i++) {
sum += arr[i];
}
System.out.println(sum);
<결과>
150
int[][] arr = {
{ 5, 5, 5, 5, 5 },
{10, 10, 10, 10, 10},
{20, 20, 20, 20, 20},
{30, 30, 30, 30, 30 }
};
int sum=0;
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr[i].length; j++) {
sum += arr[i][j];
}
}
System.out.println(sum);
float avg = sum/(float)(arr.length*arr[0].length);
System.out.printf("이차원 배열 arr의 모든 요소 값의 평균은 %.2f",avg);
======
결과
325
이차원 배열 arr의 모든 요소 값의 평균은 16.25
<첫 풀이에서 오류 발생>
// 1과 9 사이의 중복되지 않은 세 자리 수를 만드는 메소드
int a =0, b=0, c=0;
a = (int)(Math.random()*9)+1; //1에서 9까지의 정수 반환하여 a에 저장
while(true) {
b = (int)(Math.random()*9)+1;
c = (int)(Math.random()*9)+1;
if(a==b) {
b = (int)(Math.random()*9)+1;
continue;//❌.
if(a==c || b==c) {
c = (int)(Math.random()*9)+1;
} else // !(a==c || b==c)
{
break;
}
}
}
a==b
일 때 b에 1~9 사이의 수를 재할당하긴 했지만 a의 수와 다시 일치할 확률이 (*(1/9))였다. 따라서 continue;문을 사용하여 다음 조건식을 실행하지 않고 다시 while(true) 무한 반복문으로 돌아가고자 하였다.ChatGPT🧐 :
1. continue문은 현재 반복문의 실행을 중단하고, 다음 반복으로 건너뛰는 역할을 합니다. 따라서 continue문 이후의 코드는 실행되지 않고, 가장 가까운 반복문의 조건식으로 돌아가게 됩니다.
2. 하지만, continue문 이후의 코드가 있는 경우에는 continue문이 실행되지 않을 수 있기 때문에, 컴파일 에러가 발생합니다. 예를 들어, 다음과 같은 코드에서는 컴파일 에러가 발생합니다.for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; System.out.println(i); // 컴파일 에러 발생 } }
ChatGPT🧐 :
위 코드에서는 continue문 이후에 System.out.println(i);라는 코드가 있습니다. 하지만, continue문이 실행되면 System.out.println(i);는 실행되지 않습니다. 따라서, 컴파일 에러가 발생합니다.
// 1과 9 사이의 중복되지 않은 세 자리 수를 만드는 메소드
int a =0, b=0, c=0;
a = (int)(Math.random()*9)+1; //1에서 9까지의 정수 반환하여 a에 저장
while(true) {
b = (int)(Math.random()*9)+1;
c = (int)(Math.random()*9)+1;
if(a==b) {
b = (int)(Math.random()*9)+1;
continue;
}//🌟수정된 부분
if(a==c || b==c) {
c = (int)(Math.random()*9)+1;
} else // !(a==c || b==c)
{
break;
}
}
String str = new String(""+a+b+c);
int num = Integer.parseInt(str);
System.out.println(num);
<결과>
348 // 1~9 중 서로 다른 임의의 값을 가진 세 자리 수
// for(int i=0; i<100; i++) { 여기 집어넣어도 } 체크됨!
// 일차원 배열 int arr의 요소는 1~9
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int a=0, b=0, c=0;
a = arr[(int)(Math.random()*(arr.length))]; // a는 1~9까지의 정수 중 하나
// 서로 다른 세 개의 수를 뽑아보자 (서로 다른 수가 뽑힐 때 까지 무한 반복문)
for(int i=0; true; i++) {
b =arr[(int)(Math.random()*(arr.length))];
if (a==b) {
continue; // 다시 반복문으로 돌아간다.
}
c =arr[(int)(Math.random()*arr.length)];
if ((a==c)||(b==c)) {
continue;
}
break; //모든 조건(서로 다른 수 a, b, c)을 완수하면 무한반복문 빠져나감.
}
String str = new String(""+a+b+c);
int num = Integer.parseInt(str);
System.out.println(num);
// 일차원 배열 int arr의 요소는 1~9
int[] ballArr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] ball3 = new int [3]; //3개의 공을 뽑아 나열한다.
for(int i=0; i<ballArr.length; i++) {
//randomIndex는 [0~8] 사이의 인덱스가 나오도록 설정해준다.
int randomIndex = ((int)(Math.random()*ballArr.length));
int tmp = ballArr[i];
ballArr[i] = ballArr[randomIndex]; // 임의 인덱스의 요소값을 i에 저장.
ballArr[randomIndex] = tmp; // 원래 index[i]에 있던 값을 저장.
}
for(int i=0; i<ball3.length; i++) {
ball3[i] = ballArr[i];
} // ball3 = {ballArr[0], ballArr[1], ballArr[2]}; 와 같음.
System.out.println("" + ball3[0] + ball3[1] + ball3[2]);
//🔥String str을 굳이 둘 필요가 없다는 사실을 깨달았다.
//게다가 출력만 하는거라면 Integer.parseInt()를 사용할 필요 없다는 것도 깨달음
int[] ballArr = {1,2,3,4,5,6,7,8,9};
int[] ball3 = new int[3];
// 배열 ballArr의 임의의 요소를 골라서 위치를 바꾼다
for(int i=0; i< ballArr.length;i++) {
int j = (int)(Math.random() * ballArr.length);
int tmp = 0;
tmp = ballArr[i];
ballArr[i] = ballArr[j];
ballArr[j] = tmp;
}
// 배열 ballArr의 앞에서 3개의 수를 배열ball3 로 복사한다💡
System.arraycopy(ballArr,0, ball3,0,3);
for(int i=0;i<ball3.length;i++) {
System.out.print(ball3[i]);
}
System.out.println();
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
<길을 못찾아서 포기한 풀이>
//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
//단어의 2차원 배열 3행 5열
char[][] chArr = {
{'s','c','o','r','e'},
{'c','h','a','i','r'},
{'a','p','p','l','e'}
};
for(int i=0; i<chArr.length; i++) {
for(int j=0; j<chArr[i].length; j++) {
//임의의 열의 인덱스값을 반환하는 메소드 columIndex를 만들어준다.(0~4)
int columnIndex = (int)(Math.random()*chArr.length);
char tmp = chArr[i][j];
chArr[i][j] = chArr[i][columnIndex];
chArr[i][columnIndex] = tmp;
}
}
//사용자로부터 입력값을 받는다.
for(int i=0; i<chArr.length; i++) {
for(int j=0; j<chArr[i].length; j++) {
System.out.println("Q. 다음 문자를 재배열해서 정답단어를 맞춰보세요.");
System.out.print("" +chArr[i][j]); //i행의 각 열들 print로 붙이기
}
System.out.println("%n자, 방금 보여드린 단어는 무엇인가요? : ");
String input = scanner.nextLine(); //사용자에게 입력받은 값 String 변수 input에 저장
if(input==) {
}
}
(The left-hand side of an assignment must be a variable)
//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
String[]words = {
"television", "computer", "mouse", "phone"
};
// words 안의 각 문자열 요소들의 문자를 shuffle하기 위해서는 일단 개별 요소에 접근해야함.
for(int i=0; i<words.length; i++) {
String str = words[i];
// j의 값은 0부터 해당 str의 길이-1까지만큼 증가한다.
for(int j=0; j<str.length(); j++) {
int randomIndex = (int)(Math.random()*str.length());
char tmp = '0';
tmp = str.charAt(j);
😕str.charAt(j) = str.charAt(randomIndex); //The left-hand side of an assignment must be a variable
}
}
//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
String[]words = {
"television", "computer", "mouse", "phone"
};
// words 안의 각 문자열 요소들의 문자를 shuffle하기 위해서는 일단 개별 요소에 접근해야함.
for(int i=0; i<words.length; i++) {
String word = words[i];
System.out.println("다음 무작위 배열의 원래 단어를 알아맞혀보세요.");
// j의 값은 0부터 해당 str의 길이-1까지만큼 증가한다.
for(int j=0; j<word.length(); j++) {
//🤔 문자열 배열chArr를 만들어 문자배열의 각 요소에 접근하여 문자를 개별요소로 나누어 저장.
❗❗char[] chArr = new char[word.length()];
for(int k=0; k<word.length(); k++) {
// String 타입인 word를 char로 변환하여 chArr[]에 입력. charAt()메소드 사용
chArr[k] = word.charAt(k);
}❗❗
// 0~(wordlength-1)까지의 임의 정수를 반환하여 랜덤인덱스로 사용
int wordIndex = (int)(Math.random()*word.length());
//tmp에 현재 문자를 저장하고 randomIndex의 요소와 교환
char tmp = chArr[j];
//word[i] = word[wordIndex]; //❌The type of the expression must be an array type but it resolved to String
//왜냐하면 실제로 word는 String이기 때문이지. 문자열은 문자의배열이지만 char[]은 아니니 타입상 차이가 생긴다!
//chArr에 문자를 담았으므로 chArr[]배열을 이용해야지. 착각했네
chArr[j] = chArr[wordIndex];
chArr[wordIndex] = tmp;
System.out.printf("%c ",chArr[j]);
}
System.out.println("어떤 단어일까요? >");
String input = scanner.nextLine();
if(input==word) {
System.out.println("정답입니다!");
} else {
System.out.println("오답입니다 :(");
System.out.println("정답은 " + word + " 입니다!");
System.out.println();
}
}
//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
String[]words = {
"television", "computer", "mouse", "phone"
};
// words 안의 각 문자열 요소들의 문자를 shuffle하기 위해서는 일단 개별 요소에 접근해야함.
for(int i=0; i<words.length; i++) {
String word = words[i];
//🤔 문자열 배열chArr를 만들어 문자배열의 각 요소에 접근하여 문자를 개별요소로 나누어 저장.
char[] chArr = new char[word.length()];
for(int k=0; k<word.length(); k++) {
// String 타입인 word를 char로 변환하여 chArr[]에 입력. charAt()메소드 사용
chArr[k] = word.charAt(k);
}
System.out.println(Arrays.toString(chArr)); //🔥 제대로 담겼는지 확인
System.out.println("다음 무작위 배열의 원래 단어를 알아맞혀보세요.");
// j의 값은 0부터 해당 str의 길이-1까지만큼 증가한다.
for(int j=0; j<word.length(); j++) {
// 0~(wordlength-1)까지의 임의 정수를 반환하여 랜덤인덱스로 사용
int wordIndex = (int)(Math.random()*word.length());
//tmp에 현재 문자를 저장하고 randomIndex의 요소와 교환
char tmp = chArr[j];
//word[i] = word[wordIndex]; //❌The type of the expression must be an array type but it resolved to String
//왜냐하면 실제로 word는 String이기 때문이지. 문자열은 문자의배열이지만 char[]은 아니니 타입상 차이가 생긴다!
//chArr에 문자를 담았으므로 chArr[]배열을 이용해야지. 착각했네
chArr[j] = chArr[wordIndex];
chArr[wordIndex] = tmp;
System.out.printf("%c ",chArr[j]);//❗❗❗
}
System.out.println("어떤 단어일까요? >");
String input = scanner.nextLine();
if(input==word) {
System.out.println("정답입니다!");
} else {
System.out.println("오답입니다 :(");
System.out.println("정답은 " + word + " 입니다!");
System.out.println();
}
}
<결과>
[t, e, l, e, v, i, s, i, o, n]
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
s e o o s e v s e l 어떤 단어일까요? >
System.out.printf("%c ",chArr[j]);
가 한참 섞이고 있는 와중에 출력되니 당연히 중복도 생기고 생략한 부분도 생기지. 배열이 완전히 섞인 다음 출력해주는 것이 맞다!//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
String[]words = {
"television", "computer", "mouse", "phone"
};
// words 안의 각 문자열 요소들의 문자를 shuffle하기 위해서는 일단 개별 요소에 접근해야함.
for(int i=0; i<words.length; i++) {
String word = words[i];
//🤔 문자열 배열chArr를 만들어 문자배열의 각 요소에 접근하여 문자를 개별요소로 나누어 저장.
char[] chArr = new char[word.length()];
for(int k=0; k<word.length(); k++) {
// String 타입인 word를 char로 변환하여 chArr[]에 입력. charAt()메소드 사용
chArr[k] = word.charAt(k);
}
System.out.println(Arrays.toString(chArr)); //🔥 제대로 담겼는지 확인
System.out.println("다음 무작위 배열의 원래 단어를 알아맞혀보세요.");
// j의 값은 0부터 해당 word의 길이-1까지만큼 증가한다.
for(int j=0; j<word.length(); j++) {
// 0~(wordlength-1)까지의 임의 정수를 반환하여 랜덤인덱스로 사용
int wordIndex = (int)(Math.random()*word.length());
//tmp에 현재 문자를 저장하고 randomIndex의 요소와 교환
char tmp = chArr[j];
chArr[j] = chArr[wordIndex];
chArr[wordIndex] = tmp;
// System.out.printf("%c ",chArr[j]); //❗❗❗이거 때문이네!! char 배열이 다 섞이고 나서 출력해야하는데 섞이는 중에 출력하면 당연히 중복, 생략되지
}
System.out.print(Arrays.toString(chArr)+ " ");
System.out.println("어떤 단어일까요? >");
String input = scanner.nextLine();
if(input==word) {
System.out.println("정답입니다!");
} else {
System.out.println("오답입니다 :(");
System.out.println("정답은 " + word + " 입니다!");
System.out.println();
}
}
<출력>
[t, e, l, e, v, i, s, i, o, n]
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[i, i, t, e, s, e, v, l, n, o] 어떤 단어일까요? >
television // (내가 입력한 부분)
오답입니다 :( //❓❓❓ 왜... 맞게 썼잖아.
정답은 television 입니다!
[c, o, m, p, u, t, e, r]
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[m, u, o, e, c, r, t, p] 어떤 단어일까요? >
//스캐너 API로 사용자의 입력값을 받을 것
Scanner scanner = new Scanner(System.in);
String[]words = {
"television", "computer", "mouse", "phone"
};
// words 안의 각 문자열 요소들의 문자를 shuffle하기 위해서는 일단 개별 요소에 접근해야함.
for(int i=0; i<words.length; i++) {
String word = words[i];
//🤔 문자열 배열chArr를 만들어 문자배열의 각 요소에 접근하여 문자를 개별요소로 나누어 저장.
char[] chArr = new char[word.length()];
for(int k=0; k<word.length(); k++) {
// String 타입인 word를 char로 변환하여 chArr[]에 입력. charAt()메소드 사용
chArr[k] = word.charAt(k);
}
//System.out.println(Arrays.toString(chArr)); //🔥 제대로 담겼는지 확인
System.out.println("다음 무작위 배열의 원래 단어를 알아맞혀보세요.");
// j의 값은 0부터 해당 word의 길이-1까지만큼 증가한다.
for(int j=0; j<word.length(); j++) {
// 0~(wordlength-1)까지의 임의 정수를 반환하여 랜덤인덱스로 사용
int wordIndex = (int)(Math.random()*word.length());
//tmp에 현재 문자를 저장하고 randomIndex의 요소와 교환
char tmp = chArr[j];
chArr[j] = chArr[wordIndex];
chArr[wordIndex] = tmp;
// System.out.printf("%c ",chArr[j]); //❗❗❗이거 때문이네!! char 배열이 다 섞이고 나서 출력해야하는데 섞이는 중에 출력하면 당연히 중복, 생략되지
}
System.out.print(Arrays.toString(chArr)+ " ");
System.out.println("어떤 단어일까요? >");
String input = scanner.nextLine();
if(input.equals(word)) {
System.out.println("정답입니다!");
} else {
System.out.println("오답입니다 :(");
System.out.println("정답은 " + word + " 입니다!");
System.out.println();
}
}
<결과>
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[e, v, o, s, l, i, i, t, e, n] 어떤 단어일까요? >
television
정답입니다!
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[m, c, o, t, r, e, u, p] 어떤 단어일까요? >
computer
정답입니다!
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[o, u, e, m, s] 어떤 단어일까요? >
mouse
정답입니다!
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[n, e, h, p, o] 어떤 단어일까요? >
oneph
오답입니다 :(
정답은 phone 입니다!
다음 무작위 배열의 원래 단어를 알아맞혀보세요.
[y, c, p, o, l, i] 어떤 단어일까요? >
policy
정답입니다!
<모범답안>
String[] words = { "television", "computer", "mouse", "phone" };
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < words.length; i++) {
char[] question = words[i].toCharArray(); // String을 char[]로 변환
/*
(1) 알맞은 코드를 넣어 완성하시오.
char배열 question에 담긴 문자의 위치를 임의로 바꾼다.
*/
for(int j=0; j<question.length; j++) {
int randomIndex = (int)(Math.random()*question.length);
char tmp = question[j];
question[j] = question[randomIndex];
question[randomIndex] = tmp;
}
System.out.printf("Q%d. %s의 정답을 입력하세요.>",
i + 1, new String(question));
String answer = scanner.nextLine();
// trim()으로 answer의 좌우 공백을 제거한 후, equals로 word[i]와 비교
if (words[i].equals(answer.trim()))
System. out. printf("맞았습니다.%n%n");
else
System. out .printf("틀렸습니다.%n%n");
}
<결과>
Q1. eleitvnsoi의 정답을 입력하세요.>d
틀렸습니다.
Q2. curotemp의 정답을 입력하세요.>computer
맞았습니다.
Q3. mueos의 정답을 입력하세요.>mous
틀렸습니다.
Q4. nphoe의 정답을 입력하세요.>phone
맞았습니다.
chatGPT🧑🍳: char 타입 배열 안의 요소들을 묶어서 String 타입으로 변환할 수 있습니다. 이를 위해서는 String 클래스의 생성자 중 하나인 String(char[] value) 생성자를 사용하면 됩니다.
다음은 char 타입 배열을 String 타입으로 변환하는 예시 코드입니다.char[] chArr = { 'c', 'o', 'm', 'p', 'u', 't', 'e', 'r' }; String str = new String(chArr); // char 배열을 String으로 변환 System.out.println(str); // "computer" 출력
위 예시 코드에서
String
클래스의 생성자String(char[] value)
를 사용하여chArr
배열을String 객체
인str
으로 변환합니다. 그리고 str을 출력하면 "computer"가 출력됩니다.
3) String.trim( )의 사용: 공백을 제거하는 String 클래스의 메소드.