명품 자바 프로그래밍(개정5판) 3장 실습문제 풀이 p.166-173
public class WhileLoop {
public static void main(String[] args) {
int sum=0, i=1;
while(true) {
if(i > 50)
break;
sum = sum+i;
i += 3;
}
System.out.println(sum);
}
}
public class ForLoop {
public static void main(String[] args) {
int sum=0;
for(int i=1; i<50; i+=3) {
sum = sum + i;
}
System.out.println(sum);
}
}
public class DoWhileLoop {
public static void main(String[] args) {
int sum=0, i=1;
do {
sum = sum+i;
i += 3;
}while(i<50);
System.out.println(sum);
}
}
public class ForLoopArray {
public static void main(String[] args) {
int n[] = {1, -2, 6, 20, 5, 72, -16, 256};
for(int i = 0; i < n.length; i++) {
if(n[i] > 0 && n[i] % 4 == 0) {
System.out.print(n[i] + " ");
}
}
}
}
public class WhileLoopArray {
public static void main(String[] args) {
int n[] = {1, -2, 6, 20, 5, 72, -16, 256};
int i = 0;
while(i<n.length) {
if(n[i] > 0 && n[i] % 4 == 0) {
System.out.print(n[i] + " ");
}
i++;
}
}
}
public class DoWhileLoopArray {
public static void main(String[] args) {
int n[] = {1, -2, 6, 20, 5, 72, -16, 256};
int i = 0;
do {
if(n[i] > 0 && n[i] % 4 == 0) {
System.out.print(n[i] + " ");
}
i++;
} while(i < n.length);
}
}
import java.util.Scanner;
public class Star {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num;
while(true) {
System.out.print("양의 정수 입력>>");
num = scanner.nextInt();
if(num > 0)
break;
}
for(int i=0; i<num; i++) {
for(int j=0; j<num-i; j++) {
System.out.print("*");
}
System.out.println();
}
scanner.close();
}
}
import java.util.Scanner;
public class ArrayPrint {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n [][]= {{1,2,3},{1,2},{1},{1,2,3},{1,2,3,4}};
for(int i=0; i<n.length; i++) {
for(int j=0; j<n[i].length; j++) {
System.out.print(n[i][j] + "\t");
}
System.out.println();
}
scanner.close();
}
}
import java.util.Scanner;
public class MultipleOf3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n[] = new int[10];
System.out.print("양의 정수 10개 입력>>");
for(int i=0; i<n.length; i++) {
n[i]=scanner.nextInt();
}
System.out.print("3의 배수는...");
for(int i=0; i<n.length; i++) {
if(n[i] % 3 == 0)
System.out.print(n[i]+ " ");
}
scanner.close();
}
}
import java.util.Scanner;
public class DigitSumOf9 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("양의 정수 10개 입력>>");
int []n = new int[10];
for(int i=0; i<10; i++) {
n[i]=scanner.nextInt();
}
System.out.print("자리수의 합이 9인 것은 ...");
for(int j=0; j<10; j++) {
// 최대 3자리 수라고 가정
if((n[j]/100 + n[j]%100/10 + n[j]%10 )== 9) {
System.out.print(n[j] + " ");
}
}
scanner.close();
}
}
public class RandomArray {
public static void main(String[] args) {
System.out.print("랜덤한 정수들...");
int[] array = new int[10];
int sum = 0;
double avg = 0;
for(int i=0;i<10;i++) {
array[i] = (int)(Math.random()*9)+11;
System.out.print(array[i]+ " ");
sum+= array[i];
}
avg = (double)sum/array.length;
System.out.println();
System.out.print("평균은 " + avg);
}
}
import java.util.Scanner;
public class RandomArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("정수 몇 개 저장하시겠습니까>>");
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;
double avg = 0;
System.out.print("랜덤한 정수들...");
for(int i=0; i<n; i++) {
arr[i]=(int)(Math.random()*100) + 1;
System.out.print(arr[i]+ " ");
sum += arr[i];
}
avg = (double)sum/n;
System.out.println();
System.out.println("평균은 " + avg);
scanner.close();
}
}
public class FourByFourArray {
public static void main(String[] args) {
int[][] arr = new int[4][4];
System.out.println("4x4 배열에 랜덤한 값을 저장한 후 출력합니다.");
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
arr[i][j] = (int)(Math.random()*256);
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
}
}
import java.util.Scanner;
public class FourByFourArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[][] arr = new int[4][4];
System.out.println("4x4 배열에 랜덤한 값을 저장한 후 출력합니다.");
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
arr[i][j] = (int)(Math.random()*256);
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
System.out.print("임계값 입력>>");
int value = scanner.nextInt();
for(int i=0; i<4; i++) {
for(int j=0; j<4; j++) {
if(arr[i][j] > value) {
arr[i][j] = 255;
}
else {
arr[i][j] = 0;
}
System.out.print(arr[i][j] + "\t");
}
System.out.println();
}
scanner.close();
}
}
import java.util.Scanner;
public class Quiz {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("***** 구구단을 맞추는 퀴즈입니다. *****");
int x, y, ans, wrongCount = 0;
while(true) {
x = (int)(Math.random()*9) + 1;
y = (int)(Math.random()*9) + 1;
System.out.print(x + "x" + y + "=");
ans = scanner.nextInt();
if(x*y == ans) {
System.out.println("정답입니다. 잘했습니다.");
}
else {
wrongCount++;
if(wrongCount == 3) {
System.out.println(wrongCount + "번 틀렸습니다. 퀴즈 종료합니다.");
break;
}
System.out.println( wrongCount + "번 틀렸습니다. 분발하세요.");
}
}
scanner.close();
}
}
import java.util.Scanner;
public class Name {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String boyMiddleList[] = {"기", "민", "용", "종", "현", "진", "재", "승", "소", "상", "지"};
String boyLastList[] = {"태", "진", "광", "혁", "우", "철", "빈", "준", "구", "호", "석"};
String girlMiddleList[] = {"은", "원", "경", "수", "현", "예", "여", "송", "서", "채", "하"};
String girlLastList[] = {"진", "연", "경", "서", "리", "숙", "미", "원", "린", "희", "수"};
System.out.println("***** 작명 프로그램이 실행됩니다. *****");
while(true) {
System.out.print("남/여 선택>>");
String gender = scanner.next();
if(gender.equals("남")) {
System.out.print("성 입력>>");
String firstName = scanner.next();
int middle = (int)(Math.random() * boyMiddleList.length);
int last = (int)(Math.random() * boyLastList.length);
System.out.println("추천 이름: " + firstName + boyMiddleList[middle] + boyLastList[last]);
}
else if(gender.equals("여")) {
System.out.print("성 입력>>");
String firstName = scanner.next();
int middle = (int)(Math.random() * girlMiddleList.length);
int last = (int)(Math.random() * girlLastList.length);
System.out.println("추천 이름: " + firstName + girlMiddleList[middle] + girlLastList[last]);
}
else if(gender.equals("그만")) {
break;
}
else {
System.out.println("남/여/그만 중에서 입력하세요!");
}
}
scanner.close();
}
}
import java.util.Scanner;
public class Grade {
public static void main(String[] args) {
String course [] = {"C", "C++", "Python", "Java", "HTML5" };
String grade [] = {"A", "B+", "B", "A+", "D"};
Scanner scanner = new Scanner(System.in);
String courseName;
boolean isCourse;
while(true) {
isCourse = false;
System.out.print("과목>>");
courseName = scanner.next();
if(courseName.equals("그만"))
break;
for(int i=0; i<course.length; i++) {
if(course[i].equals(courseName)) {
System.out.println(courseName + " 학점은 " + grade[i]);
isCourse = true;
break;
}
}
if(!isCourse)
System.out.println(courseName + "는 없는 과목입니다.");
}
scanner.close();
}
}
import java.util.Scanner;
public class Gambling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("***** 갬블링 게임을 시작합니다. *****");
while(true) {
System.out.print("엔터키 입력>>");
scanner.nextLine();
int x = (int)(Math.random()*3);
int y = (int)(Math.random()*3);
int z = (int)(Math.random()*3);
System.out.println(x + " " + y + " " + z);
if(x==y && y==z) {
System.out.println("성공! 대박났어요!");
System.out.print("계속하시겠습니까?(yes/no)>>");
String choose = scanner.nextLine();
if(choose.equals("no")) {
System.out.println("게임을 종료합니다.");
break;
}
else if (!choose.equals("yes")) {
System.out.println("yes/no 중에 입력해주세요.");
}
}
}
scanner.close();
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class Multiply {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.print("곱하고자 하는 정수 2개 입력>>");
try {
int n = scanner.nextInt();
int m = scanner.nextInt();
System.out.print(n+ "x" + m + "=" + n*m);
break;
} catch (InputMismatchException e) {
System.out.println("정수를 입력하세요!");
scanner.nextLine();
continue;
}
}
scanner.close();
}
}
import java.util.Scanner;
public class Average {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int sum = 0, count = 0;
System.out.print("양의 정수를 입력하세요. -1은 입력 끝>>");
while(true) {
String input = scanner.next();
try {
int n = Integer.parseInt(input);
if(n == -1) break;
if (n > 0) {
sum += n;
count++;
}
else {
System.out.println(n + " 제외");
}
} catch (NumberFormatException e) {
System.out.println(input + " 제외");
}
}
if (count > 0) {
System.out.println("평균은 " + sum/count);
}
else {
System.out.println("입력된 양의 정수가 없습니다.");
}
scanner.close();
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class CafeOrder {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String coffee[] = {"핫아메리카노", "아이스아메리카노", "카푸치노", "라떼"};
int price[] = {3000, 3500, 4000, 5000};
System.out.println("핫아메리카노, 아이스아메리카노, 카푸치노, 라떼 있습니다.");
while(true) {
System.out.print("주문>>");
try {
String menu = scanner.next();
int cup = scanner.nextInt();
boolean isMenu = false;
if(menu.equals("그만")) break;
for(int i=0; i<coffee.length; i++) {
if(menu.equals(coffee[i])) {
System.out.println("가격은 " + price[i]*cup + "원입니다.");
isMenu = true;
break;
}
}
if(!isMenu) {
System.out.println(menu + "는 없는 메뉴입니다.");
}
} catch(InputMismatchException e) {
System.out.println("잔 수는 양의 정수로 입력해주세요!");
scanner.nextLine();
}
}
scanner.close();
}
}
import java.util.InputMismatchException;
import java.util.Scanner;
public class StudentScore {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("10명 학생의 학번과 점수 입력");
int[] studentNum = new int[10]; // 학번
int[] score = new int[10]; // 점수
for(int i=0; i<10; i++) {
System.out.print(i+1 + ">>");
studentNum[i]=scanner.nextInt();
score[i]=scanner.nextInt();
}
while(true) {
System.out.print("학번으로 검색: 1, 점수로 검색: 2, 끝내려면 3>>");
int menu = scanner.nextInt();
boolean found;
if(menu == 1) { // 학번으로 검색
found = false;
while(true) {
System.out.print("학번>>");
try {
int searchNum = scanner.nextInt();
for(int i=0; i<studentNum.length; i++) {
if(searchNum == studentNum[i]) {
System.out.println(score[i] + "점");
found = true;
break;
}
}
if(!found) {
System.out.println(searchNum + "의 학생은 없습니다.");
}
break;
} catch (InputMismatchException e) {
System.out.println("경고!! 정수를 입력하세요.");
scanner.nextLine();
}
}
}
else if(menu == 2) { // 점수로 검색
found = false;
while(true) {
System.out.print("점수>>");
try {
int searchScore = scanner.nextInt();
System.out.print("점수가 "+ searchScore + "인 학생은 ");
for(int i=0; i<score.length; i++) {
if(searchScore == score[i]) {
System.out.print(studentNum[i] + " ");
found = true;
}
}
if(!found) {
System.out.println("없습니다.");
}
else {
System.out.println("입니다.");
}
break;
} catch (InputMismatchException e) {
System.out.println("경고!! 정수를 입력하세요.");
scanner.nextLine();
}
}
}
else if(menu == 3) { //종료
System.out.println("프로그램을 종료합니다.");
scanner.close();
break;
}
else {
System.out.println("1, 2, 3 중 입력해주세요.");
}
}
}
}
개인 풀이이므로 틀린 부분이나 피드백이 있으면 댓글로 남겨주시면 감사하겠습니다!