이지은님의 블로그
[명품 JAVA Programming] 제7장 실습문제 본문
1. Scanner 클래스로 -1이 입력될 때까지 양의 정수를 입력받아 벡터에 저장하고 벡터를 검색하여 가장 큰 수를 출력하는 프로그램을 작성하라.
import java.util.Scanner;
import java.util.Vector;
public class Prac7_1 {
public static void main(String[] args) {
System.out.print("정수(-1)이 입력될떄까지>>");
Scanner s = new Scanner(System.in);
Vector<Integer> num = new Vector<Integer>();
int max=0;
while (true) {
int n = s.nextInt();
if (n == -1) break;
num.add(n);
if(n>max) max=n;
}
System.out.println("가장 큰 수는 "+max);
s.close();
}
}
2. Scanner 클래스를 사용하여 6개의 학점('A','B','C','D','F')을 문자로 입력받아 ArrayList에 저장하고, ArrayList를 검색하여 학점을 점수(A=4.0, B=3.0, C=2.0, D=1.0, F=0)로 변환하여 평균을 출력하는 프로그램을 작성하라.
import java.util.ArrayList;
import java.util.Scanner;
public class Prac7_2 {
public static void main(String[] args) {
System.out.print("6개의 학점을 빈칸으로 분리 입력(A/B/C/D/F)>>");
Scanner s = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<String>();
double sum = 0;
for(int i = 0; i<6; i++){
String ans = s.next();
arr.add(ans);
char a = ans.charAt(0);
if(a == 'A') sum+=4.0;
else if(a == 'B') sum+=3.0;
else if(a == 'C') sum+=2.0;
else if(a == 'D') sum+=1.0;
else if(a == 'F') sum+=0;
}
System.out.println(sum/6);
s.close();
}
}
3. "그만"이 입력될 떄까지 나라 이름과 인구를 입력받아 저장하고, 다시 나라이름을 입력 받아 인구를 출력하는 프로그램을 출력하는 프로그램을 작성하라. 다음 해시맵을 이용하라.
import java.util.HashMap;
import java.util.Scanner;
public class Prac7_3 {
public static void main(String[] args) {
System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");
Scanner sc = new Scanner(System.in);
HashMap<String,Integer> nation= new HashMap<String,Integer> ();
while (true) {
System.out.print("나라 이름, 인구 >>");
String ans = sc.nextLine();
if(ans.equals("그만")) break;
String [] anss = ans.split("\\s+");
String con = anss[0];
int pop = Integer.parseInt(anss[1]);
nation.put(con,pop);
}
while (true) {
System.out.print("인구 검색 >>");
String conKey = sc.nextLine();
if(conKey.equals("그만")) break;
Integer popValue = nation.get(conKey);
if(popValue == null) System.out.println(conKey+" 나라는 없습니다.");
else System.out.println(conKey+"의 인구는 "+popValue);
}
sc.close();
}
}
4. Vector 컬렉션을 이용하여 강수량의 평균을 유지 관리하는 프로그램을 작성하라. 강수량을 입력하면 벡터에 추가하고 현재 입력된 모든 강수량과 평균을 출력한다.
import java.util.Scanner;
import java.util.Vector;
public class Prac7_4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Vector<Integer> dic = new Vector<Integer>();
while (true) {
System.out.print("강수량 입력 (0 입력시 종료)>> ");
int ans = sc.nextInt();
if(ans == 0) break;
dic.add(ans);
int sum = 0;
int i = 0;
for (i = 0; i<dic.size();i++){
int value = dic.get(i);
System.out.print(value+" ");
sum+=value;
}
System.out.println();
System.out.println("현재 평균 "+ (sum/i));
}
sc.close();
}
}
5. 하나의 학생 정보를 나타내는 Student클래스에는 이름, 학과, 학번, 학점 평균을 저장하는 필드가 있다.
(1) 학생마다 Student 객체를 생성하고 4명의 학생 정보를 ArrayList<Student> 컬렉션에 저장한 후에, ArrayList<Student>의 모든 학생(4명) 정보를 출력하고 학생 이름을 입력받아 해당 학생의 학점 평균을 출력하는 프로그램을 작성하라.
import java.util.ArrayList;
import java.util.Scanner;
class Student{
private String name, sub;
private int num;
private double avg;
public Student() {
}
public Student(String name, String sub, int num, double avg) {
this.name = name;
this.sub = sub;
this.num = num;
this.avg = avg;
}
public String getName() {
return name;
}
public String getSub() {
return sub;
}
public int getNum() {
return num;
}
public double getAvg() {
return avg;
}
public void findStudent(String name){
if(name.equals(this.name)){
System.out.println(this.name+", "+this.sub+", "+this.num+", "+this.avg);
}
}
}
public class Prac7_5 {
public static void main(String[] args) {
System.out.println("학생 이름, 학과, 학번, 학점평균 입력하세요.");
Scanner sc = new Scanner(System.in);
ArrayList<Student> dic = new ArrayList<>();
for(int i=0; i<4;i++){
System.out.print(">>");
String [] ans = sc.nextLine().split(", ");
String name = ans[0];
String sub = ans[1];
int num = Integer.parseInt(ans[2]);
double avg = Double.parseDouble(ans[3]);
dic.add(new Student(name, sub, num, avg));
}
System.out.println("--------------------------");
for(int i=0; i<4;i++){
System.out.println("이름:"+ dic.get(i).getName());
System.out.println("학과:"+ dic.get(i).getSub());
System.out.println("학번:"+ dic.get(i).getNum());
System.out.println("학점평균:"+ dic.get(i).getAvg());
System.out.println("--------------------------");
}
while (true) {
System.out.print("학생이름 >> ");
String key = sc.nextLine();
if(key.equals("그만")) break;
for(int i = 0; i < dic.size(); i++){
Student s = dic.get(i);
s.findStudent(key);
}
}
sc.close();
}
}
(2) ArrayList<Student> 대신, HashMap<String, Student> 해시맵을 이용하여 다시 작성하라. 해시맵에서 키는 학생 이름으로 한다.
import java.util.HashMap;
import java.util.Scanner;
class Student{
private String name, sub;
private int num;
private double avg;
public Student() {
}
public Student(String name, String sub, int num, double avg) {
this.name = name;
this.sub = sub;
this.num = num;
this.avg = avg;
}
public String getName() {
return name;
}
public String getSub() {
return sub;
}
public int getNum() {
return num;
}
public double getAvg() {
return avg;
}
public void findStudent(String name){
if(name.equals(this.name)){
System.out.println(this.name+", "+this.sub+", "+this.num+", "+this.avg);
}
}
}
public class Prac7_5 {
public static void main(String[] args) {
System.out.println("학생 이름, 학과, 학번, 학점평균 입력하세요.");
Scanner sc = new Scanner(System.in);
HashMap<String, Student> dic = new HashMap<>();
for(int i=0; i<4;i++){
System.out.print(">>");
String [] ans = sc.nextLine().split(", ");
String name = ans[0];
String sub = ans[1];
int num = Integer.parseInt(ans[2]);
double avg = Double.parseDouble(ans[3]);
dic.put(name, new Student(name, sub, num, avg));
}
System.out.println("--------------------------");
for (String key : dic.keySet()) {
Student s = dic.get(key);
System.out.println("이름:"+ s.getName());
System.out.println("학과:"+ s.getSub());
System.out.println("학번:"+ s.getNum());
System.out.println("학점평균:"+ s.getAvg());
System.out.println("--------------------------");
}
while (true) {
System.out.print("학생이름 >> ");
String key = sc.nextLine();
if(key.equals("그만")) break;
Student s = dic.get(key);
if (s != null) {
s.findStudent(key);
} else {
System.out.println(key + " 학생은 존재하지 않습니다.");
}
}
sc.close();
}
}
6. 도시 이름, 위도, 경도 정보를 가진 Location 클래스를 작성하고, 도시 이름을 '키'로 하는 HashMap<String,Location> 컬렉션을 만들고, 사용자로부터 입력을 받아 4개의 도시를 저장하라. 그리고 도시 이름으로 검색하는 프로그램을 작성하라.
import java.util.HashMap;
import java.util.Scanner;
class Location{
private int x, y;
private String con;
public Location(int x, int y, String con) {
this.x = x;
this.y = y;
this.con = con;
}
public void findCon(){
System.out.print(getCon()+"\t");
System.out.print(getX()+"\t");
System.out.println(getY()+"\t");
}
public int getX() {return x;}
public int getY() {return y;}
public String getCon() {return con;}
}
public class Prac7_6 {
public static void main(String[] args) {
System.out.println("도시,경도,위도를 입력하세요.");
Scanner sc = new Scanner(System.in);
HashMap<String, Location> dic = new HashMap<>();
for(int i=0; i<4;i++){
System.out.print(">>");
String [] ans = sc.nextLine().split(", ");
String con = ans[0];
int x = Integer.parseInt(ans[1]);
int y = Integer.parseInt(ans[2]);
dic.put(con, new Location(x, y, con));
}
System.out.println("--------------------------");
for (String key : dic.keySet()) {
Location s = dic.get(key);
System.out.print(s.getCon()+"\t");
System.out.print(s.getX()+"\t");
System.out.println(s.getY()+"\t");
}
while (true) {
System.out.print("도시 이름 >> ");
String key = sc.nextLine();
if(key.equals("그만")) break;
Location s = dic.get(key);
if (s != null) {
s.findCon();
} else {
System.out.println(key + "는 없습니다.");
}
}
sc.close();
}
}
7. 이름과 학점(4.5점 만점)을 5개 입력받아 해시맵에 저장하고, 장학생 선발 기준을 입력 받아 장학생 명단을 출력하라.
import java.util.HashMap;
import java.util.Scanner;
public class Prac7_7 {
public static void main(String[] args) {
System.out.println("미래장학금관리시스템입니다.");
Scanner sc = new Scanner(System.in);
HashMap<String, Double> dic = new HashMap<>();
for(int i=0; i<5;i++){
System.out.print("이름과 학점>> ");
String [] ans = sc.nextLine().split("\\s+");
String name = ans[0];
double score = Double.parseDouble(ans[1]);
dic.put(name, score);
}
System.out.print("장학생 선발 학점 기준 입력>> ");
double stand = sc.nextDouble();
System.out.print("장학생 명단 : ");
for (String key : dic.keySet()) {
if(dic.get(key)>=stand){
System.out.print(key+" ");
}
}
System.out.println();
sc.close();
}
}
8. 고객의 일므과 포인트 점수를 관리하는 프로그램을 해시맵을 이용하여 작성하라. 프로그램은 고객의 이름과 포인트를 함꼐 저장 관리하는데, 포인트는 추가될 때마다 누적하여 저장된다.
import java.util.HashMap;
import java.util.Scanner;
public class Prac7_8 {
public static void main(String[] args) {
System.out.println("** 포인트 관리 프그램입니다 **");
Scanner sc = new Scanner(System.in);
HashMap<String, Integer> dic = new HashMap<>();
while(true){
System.out.print("이름과 포인트 입력>> ");
String ans = sc.nextLine();
if(ans.equals("그만")) break;
String anss[] = ans.split("\\s+");
if(anss.length!=2){
System.out.println("다시 입력하세요"); continue;
} else{
String key = anss[0];
int values = Integer.parseInt(anss[1]);
if(dic.containsKey(key)) {
dic.put(key, dic.get(key)+values);
}
else dic.put(key, values);
for(String keys: dic.keySet()){
System.out.print("("+keys+","+dic.get(keys)+")");
}
System.out.println();
}
}
sc.close();
}
}
9. 다음 IStack 인터페이스가 있다. IStack<T>인터페이스를 구현(implements)하는 MyStack<T> 클래스를 작성하라. 스택의 원소는 Vector<E>를 이용하여 저장하라. 다음은 MyStack<Integer>로 구체화한 정수 스택을 생성하고 활용하는 코드와 실행 결과이다.
import java.util.Vector;
interface IStack<T>{
T pop();
boolean push(T ob);
}
class MyStack<T> implements IStack<T>{
private Vector<T> stack;
private int top;
public MyStack() {
stack = new Vector<>();
top = 0;
}
@Override
public T pop() {
if(top==0){
return null;
} else{
top --;
return stack.remove(top);
}
}
@Override
public boolean push(T ob) {
top ++;
return stack.add(ob);
}
}
public class Prac7_9 {
public static void main(String[] args) {
IStack<Integer> stack = new MyStack<Integer>();
for(int i = 0; i <10; i++) stack.push(i);
while (true) {
Integer n = stack.pop();
if(n == null) break;
System.out.print(n + " ");
}
System.out.println();
}
}
10. Vector<Shape>의 벡터를 이용하여 그래픽 편집기를 만들어보자. 본문 5.6절과 5.7절에서 사례로 든 추산 클래스 Shape과 Line, Rect, Circle 클래스 코드를 잘 완성하고 이를 활용하여 "삽입", "삭제", "모두보기", "종료"의 4가지 그래픽 편집 기능을 프로그램을 작성하라. 6장 실습문제 6번을 Vector<Shape>을 이용하여 재작성하는 연습이다. Vector를 이용하면 6장 실습문제 6번보다 훨씬 간단히 작성됨을 경험할 수 있다.
package Prac7_10;
import java.util.Scanner;
import java.util.Vector;
abstract class Shape{
private Shape next;
public Shape() {next=null;}
public void setNext(Shape obj) {next= obj;}
public Shape getNext() {return next;}
public abstract void draw();
}
class Line extends Shape{
@Override
public void draw() {
System.out.println("Line");
}
}
class Rect extends Shape{
@Override
public void draw() {
System.out.println("Rect");
}
}
class Circle extends Shape{
@Override
public void draw() {
System.out.println("Circle");
}
}
class GraphicEditor{
private Vector<Shape> vec = new Vector<Shape>();
public void insert(int n){
Shape s;
if(n==1){
s = new Line();
vec.add(s);
} else if(n==2){
s = new Rect();
vec.add(s);
} else if(n==3){
s = new Circle();
vec.add(s);
}
}
public void delete(int n){
if(vec.size()<n) System.out.println("삭제할 수 없습니다.");
else vec.remove(n-1);
}
public void show(){
for (int i=0;i<vec.size();i++){
vec.get(i).draw();
}
}
}
public class Prac7_10 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("그래픽 에디터 beauty을 실행합니다.");
GraphicEditor beauty = new GraphicEditor();
while (true) {
System.out.print("삽입(1), 삭제(2), 모두보기(3), 종료(4)>>");
int ans = scanner.nextInt();
if(ans==4) break;
if(ans==1) {
System.out.print("Line(1), Rect(2), Circle(3)>>");
int ansShape = scanner.nextInt();
beauty.insert(ansShape);
} else if(ans==2){
System.out.print("삭제할 도형의 위치>>");
int ansShape = scanner.nextInt();
beauty.delete(ansShape);
} else if(ans==3){
beauty.show();
}
}
System.out.println("beauty를 종료합니다.");
scanner.close();
}
}
11. 나라와 수도 맞추기 게임의 실행 예시는 다음과 같다.
(1) 나라이름(country)와 수도(capital)로 구성된 Nation 클래스를 작성하고 Vector<Nation>컬렉션을 이용하여 프로그램을 작성하라.
import java.util.Scanner;
import java.util.Vector;
class Nation{
private String country, capital;
public Nation(String country, String capital) {
this.country = country;
this.capital = capital;
}
public String getCountry() {return country;}
public String getCapital() {return capital;}
}
class CountryQuiz{
private Vector<Nation> dic = new Vector<Nation>();
public CountryQuiz(){
dic.add(new Nation("그리스","아테네"));
dic.add(new Nation("독일","베를린"));
dic.add(new Nation("멕시코","멕시코시티"));
dic.add(new Nation("영국","런던"));
dic.add(new Nation("중국","베이징"));
dic.add(new Nation("프랑스","파리"));
dic.add(new Nation("일본","도쿄"));
dic.add(new Nation("러시아","모스크바"));
dic.add(new Nation("스페인","마드리드"));
}
public void show(){
System.out.println("현재 "+dicSize()+"개 나라와 수도가 입력되어 있습니다.");
}
public int dicSize(){ return dic.size(); }
public void input(String key, String value){
for(int i = 0; i<dic.size();i++){
if(dic.get(i).getCountry().equals(key)){
System.out.println(key+"는 이미 있습니다!");
return;
}
}
dic.add(new Nation(key, value));
}
public boolean question(Scanner sc){
int n = (int) (Math.random()*dicSize());
Nation nation = dic.get(n);
System.out.print(nation.getCountry()+"의 수도는? ");
String ans = sc.next();
if (ans.equals("그만")) {
return false;
} else{
if(ans.equals(nation.getCapital())) System.out.println("정답!!");
else System.out.println("아닙니다!!");
return true;
}
}
}
public class Prac7_11 {
public static void main(String[] args) {
System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
CountryQuiz quiz = new CountryQuiz();
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("입력:1, 퀴즈:2, 종료:3>> ");
int num = sc.nextInt();
sc.nextLine();
if(num==3) {
System.out.println("게임을 종료합니다.");
break;
} else if(num==1){
quiz.show();
while (true) {
System.out.print("나라와 수도 입력"+(quiz.dicSize()+1)+">> ");
String inputAns = sc.nextLine();
if (inputAns.equals("그만")) break;
String[] inputs = inputAns.split("\\s+");
if (inputs.length != 2) {
System.out.println("잘못된 입력입니다. '나라 수도' 형식으로 입력하세요.");
continue;
}
quiz.input(inputs[0], inputs[1]);
}
} else if(num==2){
while (true) {
if(!quiz.question(sc)) break;
}
}
}
sc.close();
}
}
(2) 이 프로그램을 HashMap<String, String>을 이용하여 작성하라. '키'는 나라 이름이고 '값'은 수도이다.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
class CountryQuiz{
private HashMap<String, String> dic = new HashMap<>();
public CountryQuiz(){
dic.put("그리스","아테네");
dic.put("독일","베를린");
dic.put("멕시코","멕시코시티");
dic.put("영국","런던");
dic.put("중국","베이징");
dic.put("프랑스","파리");
dic.put("일본","도쿄");
dic.put("러시아","모스크바");
dic.put("스페인","마드리드");
}
public void show(){
System.out.println("현재 "+dicSize()+"개 나라와 수도가 입력되어 있습니다.");
}
public int dicSize(){ return dic.size(); }
public void input(String key, String value){
for(String string: dic.keySet()){
if(string.equals(key)){
System.out.println(key+"는 이미 있습니다!");
return;
}
}
dic.put(key, value);
}
public boolean question(Scanner sc){
int n = (int) (Math.random()*dicSize());
ArrayList<String> keys = new ArrayList<>(dic.keySet());
String q = keys.get(n);
System.out.print(q+"의 수도는? ");
String ans = sc.next();
if (ans.equals("그만")) {
return false;
} else{
if(ans.equals(dic.get(q))) System.out.println("정답!!");
else System.out.println("아닙니다!!");
return true;
}
}
}
public class Prac7_11 {
public static void main(String[] args) {
System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
CountryQuiz quiz = new CountryQuiz();
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("입력:1, 퀴즈:2, 종료:3>> ");
int num = sc.nextInt();
sc.nextLine();
if(num==3) {
System.out.println("게임을 종료합니다.");
break;
} else if(num==1){
quiz.show();
while (true) {
System.out.print("나라와 수도 입력"+(quiz.dicSize()+1)+">> ");
String inputAns = sc.nextLine();
if (inputAns.equals("그만")) break;
String[] inputs = inputAns.split("\\s+");
if (inputs.length != 2) {
System.out.println("잘못된 입력입니다. '나라 수도' 형식으로 입력하세요.");
continue;
}
quiz.input(inputs[0], inputs[1]);
}
} else if(num==2){
while (true) {
if(!quiz.question(sc)) break;
}
}
}
sc.close();
}
}
12. Open Challenge를 수정하여 사용자가 단어를 삽입할 수 있도록 기능을 추가하라.
import java.util.Scanner;
import java.util.Vector;
class Word{
private String eng,kor;
public Word(String eng, String kor) {
this.eng = eng;
this.kor = kor;
}
public String getEng() {return eng;}
public String getKor() {return kor;}
}
class WordQuiz{
private Vector<Word> v = new Vector<>();
public WordQuiz() {
v.add(new Word("love","사랑"));
v.add(new Word("animal","동물"));
v.add(new Word("painting","그림"));
v.add(new Word("bear","곰"));
v.add(new Word("eye","눈"));
v.add(new Word("picture","사진"));
v.add(new Word("society","사회"));
v.add(new Word("human","인간"));
v.add(new Word("baby","아기"));
v.add(new Word("error","오류"));
v.add(new Word("doll","인형"));
v.add(new Word("look","보기"));
v.add(new Word("transmit","거래"));
v.add(new Word("statue","조각상"));
v.add(new Word("family","가족"));
v.add(new Word("freind","친구"));
v.add(new Word("apple","사과"));
}
public int getSize(){
return v.size();
}
public void show(){
System.out.println("현재 "+getSize()+"개의 단어가 들어 있습니다.");
}
public void run(Scanner sc){
show();
while(true){
int n = (int) (Math.random()* getSize());
Word question = v.get(n);
System.out.println(question.getEng()+"?");
//보기 생성
int[] arr = {-1, -1, -1, -1};
for(int i=0;i<arr.length;i++){
int ranInt = (int) (Math.random()* getSize());
if(n==ranInt){
i--; continue;
} else{
arr[i] = ranInt;
}
}
int ranQues = (int) (Math.random()*4);
arr[ranQues] = n;
for(int i=0;i<arr.length;i++){
System.out.print("("+(i+1)+")"+v.get(arr[i]).getKor()+" ");
}
System.out.print(" :>");
int ans = sc.nextInt();
if(ans == -1) break;
else if (ans>=1 && ans<=4){
if(arr[ans-1] == n) System.out.println("Excellent !!");
else System.out.println("No. !!");
}
else{
System.out.println("1에서 4까지의 숫자를 입력해주세요.");
}
}
}
public void input(Scanner sc){
System.out.println("영어 단어에 그만을 입력하면 입력을 종료합니다.");
while (true) {
System.out.print("영어 한글 입력 >>");
String words = sc.nextLine();
if(words.equals("그만")) break;
String wordSplit[] = words.split("\\s+");
if(wordSplit.length!=2){
System.out.println("다시 입력해주세요.");
continue;
} else{
String eng = wordSplit[0];
String kor = wordSplit[1];
v.add(new Word(eng, kor));
}
}
}
}
public class Prac7_12 {
public static void main(String[] args) {
System.out.println("\"명품영어\"의 단어 테스트를 시작합니다. -1을 입력하면 종료합니다.");
WordQuiz q = new WordQuiz();
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("단어 테스트:1, 단어 삽입:2, 종료:3>>");
int mainAns = sc.nextInt();
sc.nextLine();
if(mainAns == 3){
break;
}
if(mainAns == 1){
q.run(sc);
} else if(mainAns==2){
q.input(sc);
}
}
System.out.println("\"명품영어\"를 종료합니다...");
sc.close();
}
}
'java 연습문제' 카테고리의 다른 글
[명품 JAVA Programming] 제6장 실습문제 (0) | 2024.12.12 |
---|---|
[명품 JAVA Programming] 제5장 실습문제 (0) | 2024.12.12 |
[명품 JAVA Programming] 제4장 실습문제 (0) | 2024.12.09 |
[명품 JAVA Programming] 제2장 실습문제 (0) | 2024.12.04 |