Java/스터디 예제 풀이

15장 제네릭과 컬렉션 연습 문제 및 LAB 문제-3

안정민 2023. 3. 3. 12:54

11. 이름과 학점(4.5만점)을 5개 입력받아 해시맵에 저장하고, 장학생 선발 기준을 입력 받아 장학생 명단을 출력하라.

미래장학금관리시스템입니다.

이름과 학점 >> 적당히 3.1

이름과 학점 >> 나탈락 2.4

이름과 학점 >> 최고조 4.3

이름과 학점 >> 상당히 3.9

이름과 학점 >> 고득점 4.0

장학생 선발 학점 기준 입력 >> 3.2

장학생 명단 : 최고조 상당히 고득점 

[Hint] HashMap의 전체 요소를 검색하여 학점이 3.2 이상인 학생을 알아내야 한다. 예제 7-6은 해시맵 전체를 검색하는 코드 사례를 보여준다.

 

package 제네릭과컬렉션;
import java.util.*;
public class Scholarship {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<String, Double> scholar=new HashMap<String, Double>();
		Scanner input=new Scanner(System.in);
		System.out.println("미래장학금관리시스템입니다.");
		
		for(int i=0;i<5;i++) {
			System.out.print("이름과 학점 >> ");
			String name=input.next();
			Double score=input.nextDouble();
			scholar.put(name,score);
		}
		
		
		System.out.print("장학생 선발 학점 기준 입력 >> ");
		Double cutline=input.nextDouble();
		System.out.print("장학생 명단 : ");
		Set<String> nameSet = scholar.keySet();
		Iterator<String> it = nameSet.iterator();
		while(it.hasNext()) {
			String name = it.next();
			double score = scholar.get(name);
			if(score > cutline)
				System.out.print(name+ " ");
		}
		System.out.println();
	}

12. 고객의 이름과 포인트 점수를 관리하는 프로그램을 해시맵을 이용하여 작성하라. 프로그램은 고객의 이름과 포인트를 함께 저장 관리하는데, 포인트는 추가될 때마다 누적하여 저장된다.

** 포인트 관리 프로그램입니다 **

이름과 포인트 입력 >> 이재문 40

(이재문,40)

이름과 포인트 입력 >> 황기태 50

(이재문,40)(황기태,50)

이름과 포인트 입력 >> 황기태 60

(이재문,40)(황기태,110)

이름과 포인트 입력 >> 김남윤 30

(이재문,40)(김남윤,30)(황기태,110)

이름과 포인트 입력 >> 이재문 20

(이재문,60)(김남윤,30)(황기태,110)

이름과 포인트 입력 >> 그만

package 제네릭과컬렉션;
import java.util.*;
public class PointManage {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashMap<String, Integer> list=new HashMap<String, Integer>();
		Scanner input=new Scanner(System.in);
		System.out.println("** 포인트 관리 프로그램입니다 **");
		while(true) {
			System.out.println("이름과 포인트 입력 >> ");
			String name=input.next();
			if(name=="그만") {
				break;
			}
			int point=input.nextInt();
			if(list.containsKey(name)==true)
				list.put(name, list.get(name)+point);
			else
				list.put(name, point);
		}
		Set<String> key = list.keySet();
		Iterator<String> it = key.iterator();
		while(it.hasNext()) {
			String people = it.next();
			Integer sum = list.get(people);
			System.out.print("("+people+","+sum+")");
		}
		System.out.println();
		
	}

13. 다음 Istack 인터페이스가 있다.

interface IStack<T> {
T pop();
boolean push(T ob);
}

IStack<T> 인터페이스를 구현(implements)하는 MyStack<T> 클래스를 작성하라. 스택의 원소는 Vector<E>를 이용하여 저장하라. 다음은 MyStack<Integer>로 구체화한 정수 스택을 생성하고 활용하는 코드와 실행 결과이다.

public class StackManager {
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+" ");
}
}
}

9 8 7 6 5 4 3 2 1 0

package IStack;
import java.util.*;

interface IStack<T> {
	T pop();
	boolean push(T ob);
}


class MyStack<T> implements IStack<T>{
	private Vector<T> vc;
	private int index;
	
	public MyStack (){
		vc=new Vector<T>();
		index=-1;
	}
	
	public T pop() {
		if(index==-1) return null;
		return vc.get(index--);
	}
	public boolean push(T ob) {
		vc.add(ob);
		index++;
		return true;
	}
}

public class StackManager {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		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.println(n+" ");
		}
	}

}​

14. Vector<Shape>의 벡터를 이용하여 그래픽 편집기를 만들어보자. 본문 5.6절과 5.7절에서 사례로 든 추상 클래스 Shape과 Line, Rect, Circle 클래스 코드를 잘 완성하고 이를 활용하여 "삽입", "삭제", "모두 보기", "종료"의 4가지 그래픽 편집 기능을 프로그램을 작성하라. 6장 실습문제 6번을 Vector<Shape>을 이용하여 재작성하는 연습이다. Vector를 이용하면 6장 실습문제 6번보다 훨씬 간단히 작성됨을 경험할 수 있다.

package 제네릭과컬렉션;
import java.util.Scanner;
import java.util.Vector;

abstract class Shape{
	public Shape() {
	}
	public abstract void draw();
}
 
class Line extends Shape{
	public Line() {
		super();
	}
	public void draw() {
		System.out.println("Line");
	}
}
 
class Rect extends Shape{
	public Rect() {
		super();
	}
	public void draw() {
		System.out.println("Rect");
	}
}
 
class Circle extends Shape{
	public Circle() {
		super();
	}
	public void draw() {
		System.out.println("Circle");
	}
}

public class GraphicEditor {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Vector<Shape> v=new Vector<Shape>();
		Scanner input=new Scanner(System.in);
		System.out.println("그래픽 에디터 beauty을 실행합니다.");
		System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4) >>> ");
		int num=input.nextInt();
		if(num==1) {
			System.out.print("Line(1), Rect(2), Circle(3) >>> ");
			int insertnum=input.nextInt();
			Shape g; // 객체 생성
			if(insertnum==1)
				g=new Line();
			else if(insertnum==2)
				g=new Rect();
			else if(insertnum==3)
				g=new Circle();
			else
				System.out.println("다시입력해주세요");
				
		}
		else if(num==2) {
			System.out.print("삭제할 도형의 위치>>");
			int index=input.nextInt();
			if(index>v.size()) {
				System.out.println("삭제할 수 없습니다.");
				return;
			}
			v.remove(index);
		}
		else if(num==3) {
			for(int i=0;i<v.size();i++) {
				v.get(i).draw();
			}
		}
		else
			System.out.println("beauty을 종료합니다.");
			
			
		
	}

}

15. 나라와 수도 맞추기 게임의 실행

package 수도;
import java.util.*;


class quiz{
	private Vector<Nation> v=new Vector<Nation>();
	Scanner sc=new Scanner(System.in);
	public quiz() {
		v.add(new Nation("멕시코","멕시코시티"));
		v.add(new Nation("스페인","리스본"));
		v.add(new Nation("프랑스","파리"));
		v.add(new Nation("영국","런던"));
		v.add(new Nation("그리스","아테네"));
		v.add(new Nation("독일","베를린"));
		v.add(new Nation("일본","동경"));
		v.add(new Nation("중국","베이징"));
		v.add(new Nation("러시아","모스크바"));
	}
	
	public void run() {
		System.out.println("**** 수도 맞추기 게임을 시작합니다. ****");
		while(true) {
			System.out.print("입력:1, 퀴즈:2, 종료:3>> ");
			int op=sc.nextInt();
			if(op==1) {
				input();
			}
			else if(op==2) {
				quizgame();
			}
			else {
				System.out.print("게임을 종료합니다.");
				break;
			}
		}
	}
	
	public void input() {
		System.out.println("현재 "+v.size()+"개 나라와 수도가 입력되어 있습니다.");
		while(true) {
			System.out.print("나라와 수도 입력"+(v.size()+1)+">> ");
			String nation=sc.next();
			if(nation.equals("그만")) {
				break;
			}
			String capital=sc.next();
			boolean flag=true;
			for(int i=0;i<v.size();i++) {
				if(v.get(i).getNation().equals(nation)){
					System.out.println(nation+"는 이미 있습니다!");
					flag=false;
					break;
				}
			}
			if(flag) {
				v.add(new Nation(nation,capital));
			}
		}
	}
	public void quizgame() {
		while(true) {
			int index=(int)(Math.random()*v.size());
			
			Nation n=v.get(index);
			String nation=n.getNation();
			String capital=n.getCapital();
			System.out.print(nation+"의 수도는? ");
			String answer=sc.next();
			
			if(answer.equals("그만")) {
				break;
			}
			
			if(answer.equals(capital)) {
				System.out.println("정답!");
			}
			else {
				System.out.println("아닙니다!");
			}
		}
	}
}
 
class Nation{
	private String nation,capital;
	public Nation(String nation,String capital) {
		this.nation=nation;
		this.capital=capital;
	}
	public String getNation() {
		return nation;
	}
	public String getCapital() {
		return capital;
	}
}

public class CapitalGame {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		quiz q=new quiz();
		q.run();
	}
}

16. Vector MaxValue

public class VectorClass {
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Vector vc=new Vector();
		int a;
		int  maxValue=0;
		System.out.print("정수 (-1이 입력될 때까지) >> ");
		
		do {
			Scanner input=new Scanner(System.in);
			a=input.nextInt();
			vc.add(a);
		} while(a!=-1);
		
		for(int i=0;i<vc.size();i++) {
			if(maxValue<(int)vc.get(i))
				maxValue=(int)vc.get(i);
		}
		
		System.out.println("가장 큰 수는 "+ maxValue);
	
	}
}