[Java] 자바의 정석
[Java] 자바의 정석 / chap5.배열_연습문제
sweetychocoding
2023. 9. 1. 09:54
728x90
5-3)
package j04_Array;
public class Ex_example {
public static void main(String[] args) {
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);
}
}

5-4)
package j04_Array;
public class Ex_example {
public static void main(String[] args) {
int[] [] arr = {
{5, 5, 5, 5, 5},
{10, 10, 10, 10, 10},
{20, 20, 20, 20, 20},
{30, 30, 30, 30, 30}
};
int total = 0;
float average = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
total += arr[i][j];
}
}
average = (float)total / (arr.length * arr[0].length);
System.out.println("total => " + total);
System.out.println("average => " + average);
}
}

5-5)
package j04_Array;
public class Ex_example {
public static void main(String[] args) {
int[] ballArr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] ball3 = new int[3];
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;
}
System.arraycopy(ballArr, 0, ball3, 0, 3);
for (int i = 0; i < ball3.length; i++) {
System.out.print(ball3[i]);
}
}
}

5-6)
package j04_Array;
import java.util.Scanner;
public class Ex_example {
public static void main(String[] args) {
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();
char randomNum = (char)((int)(Math.random() * question.length));
char temp = ' ';
temp = question[i];
question[i] = question[randomNum];
question[randomNum] = temp;
System.out.printf("Q%d. %s의 정답을 입력하세요. > ", i + 1, new String(question));
String answer = scanner.nextLine();
if (words[i].equals(answer.trim())) {
System.out.printf("맞았습니다. %n%n");
} else {
System.out.printf("틀렸습니다. %n%n");
}
}
}
}
..................섞여서 나오긴 하는데 다시 생각해봐야 할 것 같다.....
+ 추가)
아니 나 바보야???????????????????? 왜 randomNum을 char로 받음?????????
어이 아리마셍
package j04_Array;
import java.util.Scanner;
public class Ex_example {
public static void main(String[] args) {
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();
int num = (int)(Math.random() * question.length);
char temp;
for (int j = 0; j < question.length; j++) {
temp = question[j];
question[j] = question[num];
question[num] = temp;
}
System.out.printf("Q%d. %s의 정답을 입력하세요. > ", i + 1, new String(question));
String answer = scanner.nextLine();
if (words[i].equals(answer.trim())) {
System.out.printf("맞았습니다. %n%n");
} else {
System.out.printf("틀렸습니다. %n%n");
}
}
}
}

728x90