• 명품 자바 프로그래밍(개정4판) 제 7장 실습문제

    2020. 12. 7.

    by. Hyeon-Uk

    반응형

    [1번]

    import java.util.Scanner;
    import java.util.Vector;
    
    public class p0701 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		Vector<Integer> v=new Vector<Integer>();
    		System.out.print("정수(-1이 입력될 때까지)>> ");
    		while(true) {
    			int n=sc.nextInt();
    			if(n==-1) {
    				break;
    			}
    			v.add(n);
    		}
    		//최댓값 찾기위해 max를 0번째 수로 설정
    		int max=v.get(0);
    		for(int i=1;i<v.size();i++) {
    			if(max<v.get(i)) {
    				max=v.get(i);
    			}
    		}
    		System.out.println("가장 큰 수는 "+max);
    	}
    
    }
    

    [2번]

    import java.util.ArrayList;
    import java.util.Scanner;
    public class p0702 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		ArrayList<Character> arr=new ArrayList<Character>();
    		System.out.print("6개의 학점을 빈 칸으로 분리 입력(A/B/C/D/F)>> ");
    		
    		for(int i=0;i<6;i++) {
    			char c=sc.next().charAt(0);
    			arr.add(c);
    		}
    		
    		double sum=0;
    		for(int i=0;i<6;i++) {
    			switch(arr.get(i)) {
    			case 'A':
    				sum+=4.0;
    				break;
    			case 'B':
    				sum+=3.0;
    				break;
    			case 'C':
    				sum+=2.0;
    				break;
    			case 'D':
    				sum+=1.0;
    				break;
    			case 'F':
    				sum+=0;
    				break;
    			}
    		}
    		System.out.println(sum/6);
    	}
    
    }
    

    [3번]

    import java.util.HashMap;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    public class p0703 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		System.out.println("나라 이름과 인구를 입력하세요.(예: Korea 5000)");
    		HashMap<String,String> nations=new HashMap<String,String>();
    		while(true) {
    			System.out.print("나라 이름, 인구 >>");
    			String st=sc.nextLine();
    			if(st.equals("그만")) {
    				break;
    			}
                //토큰나이저를 통해 나라이름과 인구수를 구분지어 해쉬에 put
    			StringTokenizer t=new StringTokenizer(st," ");
    			String nation=t.nextToken();
    			String number=t.nextToken();
    			nations.put(nation, number);
    		}
    		while(true) {
    			System.out.print("인구 검색 >> ");
    			String st=sc.next();
    			if(st.equals("그만")) {
    				break;
    			}
    			if(nations.get(st)==null) {
    				System.out.println(st+" 나라는 없습니다.");
    			}
    			else {
    				System.out.println(st+"의 인구는 "+nations.get(st));
    			}
    		}
    	}
    }
    

    [4번]

    import java.util.Scanner;
    import java.util.Vector;
    public class p0704 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		Vector<Integer> v=new Vector<Integer>();
    		
    		while(true) {
    			System.out.print("강수량 입력 (0 입력시 종료)>> ");
    			int n=sc.nextInt();
    			if(n==0) {
    				break;
    			}
    			v.add(n);
    			int sum=0;
    			for(int i=0;i<v.size();i++) {
    				int data=v.get(i);
    				System.out.print(data+" ");
    				sum+=data;
    			}
    			System.out.println();
    			System.out.println("현재 평균 "+sum/v.size());
    		}
    	}
    }
    

    [5번]

    import java.util.ArrayList;
    import java.util.Scanner;
    import java.util.StringTokenizer;
    class Student{
    	private String name,department,studentId,avg;
    	
    	public Student(String name,String department,String studentId,String avg) {
    		this.name=name;
    		this.department=department;
    		this.studentId=studentId;
    		this.avg=avg;
    	}
    	public String getName() {
    		return name;
    	}
    	public void show() {
    		System.out.println("이름:"+name);
    		System.out.println("학과:"+department);
    		System.out.println("학번:"+studentId);
    		System.out.println("학점평균:"+avg);
    	}
    	public void find() {
    		System.out.println(name+","+department+","+studentId+","+avg);
    	}
    }
    
    public class p0705 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		ArrayList<Student> arr=new ArrayList<Student>();
    		System.out.println("학생 이름,학과,학번,학점 평균 입력하세요.");
    		for(int i=0;i<4;i++) {
    			System.out.print(">> ");
    			String st=sc.nextLine();
    			StringTokenizer t=new StringTokenizer(st,",");
    			//토크나이저후, 앞뒤 공백제거
    			String name=t.nextToken().trim();
    			String department=t.nextToken().trim();
    			String studentId=t.nextToken().trim();
    			String avg=t.nextToken().trim();
    			arr.add(new Student(name,department,studentId,avg));
    		}
    		for(int i=0;i<4;i++) {
    			System.out.println("--------------------------");
    			arr.get(i).show();
    		}
    		System.out.println("--------------------------");
    		
    		while(true) {
    			System.out.print("학생 이름 >> ");
    			String st=sc.next();
    			if(st.equals("그만")) {
    				break;
    			}
    			for(int i=0;i<4;i++) {
    				if(arr.get(i).getName().equals(st)) {
    					arr.get(i).find();
    					break;
    				}
    			}
    		}
    		sc.close();
    	}
    }
    

    반응형

    [6번]

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.StringTokenizer;
    class Location{
    	private String city;
    	private int latitude,longitude;
    	
    	public Location(String city,int longitude,int latitude) {
    		this.latitude=latitude;
    		this.longitude=longitude;
    		this.city=city;
    	}
    	public void show() {
    		System.out.println(city+"\t"+longitude+"\t"+latitude);
    	}
    	
    }
    public class p0706 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		HashMap<String, Location> h=new HashMap<String,Location>();
    		System.out.println("도시,경도,위도를 입력하세요.");
    		for(int i=0;i<4;i++) {
    			System.out.print(">> ");
    			String st=sc.nextLine();
    			StringTokenizer t=new StringTokenizer(st,",");
    			//토크나이저후, 앞뒤 공백제거
    			String city=t.nextToken().trim();
    			int longitude=Integer.parseInt(t.nextToken().trim());
    			int latitude=Integer.parseInt(t.nextToken().trim());
    			h.put(city,new Location(city,longitude,latitude));
    		}
    		Set<String> keys=h.keySet();
    		Iterator<String> it=keys.iterator();
    		System.out.println("--------------------------");
    		while(it.hasNext()) {
    			String n=it.next();
    			Location l=h.get(n);
    			l.show();
    		}
    		System.out.println("--------------------------");
    		
    		while(true) {
    			System.out.print("도시 이름 >> ");
    			String st=sc.next();
    			if(st.equals("그만")) {
    				break;
    			}
    			if(h.get(st)!=null) {
    				h.get(st).show();
    			}
    			else {
    				System.out.println(st+"는 없습니다.");
    			}
    		}
    		sc.close();
    	}
    }
    

    [7번]

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.StringTokenizer;
    
    public class p0707 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		HashMap<String, Double> h=new HashMap<String,Double>();
    		System.out.println("미래장학금관리시스템입니다.");
    		
    		for(int i=0;i<5;i++) {
    			System.out.print("이름과 학점>> ");
    			String st=sc.nextLine();
    			StringTokenizer t=new StringTokenizer(st," ");
    			//토크나이저후, 앞뒤 공백제거
    			String name=t.nextToken().trim();
    			double score=Double.parseDouble(t.nextToken().trim());
    			h.put(name,score);
    		}
    		
    		System.out.print("장학생 선발 학점 기준 입력>> ");
    		double flag=sc.nextDouble();
    		
    		Set<String> keys=h.keySet();
    		Iterator<String> it=keys.iterator();
    		
    		System.out.print("장학생 명단 : ");
    		while(it.hasNext()) {
    			String name=it.next();
    			double score=h.get(name);
    			if(flag<=score) {
    				System.out.print(name+" ");
    			}
    		}
    		sc.close();
    	}
    }
    

    [8번]

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.StringTokenizer;
    
    public class p0708 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		HashMap<String, Integer> h=new HashMap<String,Integer>();
    		System.out.println("** 포인트 관리 프로그램입니다 **");
    		
    		while(true) {
    			System.out.print("이름과 포인트 입력>> ");
    			String st=sc.nextLine();
    			if(st.equals("그만")) {
    				break;
    			}
    			StringTokenizer t=new StringTokenizer(st," ");
    			//토크나이저후, 앞뒤 공백제거
    			String name=t.nextToken().trim();
    			int point=Integer.parseInt(t.nextToken().trim());
    			if(h.get(name)!=null) {
    				int temp=h.get(name);
    				h.put(name, temp+point);
    			}
    			else {
    				h.put(name,point);
    			}
    			Set<String> keys=h.keySet();
    			Iterator<String> it=keys.iterator();
    			while(it.hasNext()) {
    				String n=it.next();
    				int p=h.get(n);
    				System.out.print("("+n+","+p+")");
    			}
    			System.out.println();
    		}
    	}		
    }
    
    

    [9번]

    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.StringTokenizer;
    import java.util.Vector;
    interface IStack<T>{
    	T pop();
    	boolean push(T ob);
    }
    
    class MyStack<T> implements IStack<T>{
    	private Vector<T> v;
    	private int size;
    	public MyStack (){
    		v=new Vector<T>();
    		size=-1;
    	}
    	public T pop() {
    		// TODO Auto-generated method stub
    		if(size==-1) return null;
    		return v.get(size--);
    	}
    
    	public boolean push(T ob) {
    		v.add(ob);
    		size++;
    		return true;
    	}
    	
    }
    
    public class p0709 {
    	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.print(n+" ");
    		}
    	}		
    }
    
    

    [10번]

    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");
    	}
    }
    
    class GraphicEditor{
    	private Shape head,tail;
    	private Scanner sc;
    	Vector<Shape> v;
    	//기본생성자
    	public GraphicEditor(){
    		v=new Vector<Shape>();
    		head=null;
    		tail=null;
    		sc=new Scanner(System.in);
    	}
    	
    	//에디터 실행 메서드
    	void runEditor() {
    		int choice;
    		System.out.println("그래픽 에디터 beauty을 실행합니다.");
    		
    		do {
    		System.out.print("삽입(1), 삭제(2), 모두 보기(3), 종료(4)>>");
    		choice=sc.nextInt();
    			switch(choice) {
    			case 1:
    				System.out.print("Line(1), Rect(2), Circle(3)>>");
    				int option=sc.nextInt();
    				put(option);
    				break;
    			case 2:
    				System.out.print("삭제할 도형의 위치>>");
    				int index=sc.nextInt();
    				delete(index);
    				break;
    			case 3:
    				print();
    				break;
    			case 4:
    				break;
    			default:
    				System.out.println("다시 입력해주세요");
    				break;
    			}
    		}while(choice!=4);
    		System.out.println("beauty을 종료합니다.");
    	}
    	
    	//리스트에 넣는 메서드
    	void put(int num) {
    		Shape g;
    		//입력번호에 따라 Line,Rect,Circle객체 생성
    		switch(num) {
    		case 1:
    			g=new Line();
    			break;
    		case 2:
    			g=new Rect();
    			break;
    		case 3:
    			g=new Circle();
    			break;
    		default:
    			System.out.println("다시입력해주세요");
    			return;
    		}
    		v.add(g);
    		return;
    	}
    	void delete(int index) {
    		if(index>v.size()) {
    			System.out.println("삭제할 수 없습니다.");
    			return;
    		}
    		v.remove(index);
    	}
    	
    	void print() {
    		for(int i=0;i<v.size();i++) {
    			v.get(i).draw();
    		}
    	}
    }
    
    public class p0710 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		GraphicEditor ge=new GraphicEditor();
    		ge.runEditor();
    	}		
    }
    
    

    [11-1번]

    import java.util.Scanner;
    import java.util.Vector;
    
    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 {
    				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 p0711 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		quiz q=new quiz();
    		q.run();
    	}
    }
    
    

    [11-2번]

     

    import java.util.HashMap;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.Vector;
    
    class quiz{
    	private HashMap<String,String>h =new HashMap<String,String>();
    	Scanner sc=new Scanner(System.in);
    	public quiz() {
    		h.put("멕시코","멕시코시티");
    		h.put("스페인","리스본");
    		h.put("프랑스","파리");
    		h.put("영국","런던");
    		h.put("그리스","아테네");
    		h.put("독일","베를린");
    		h.put("일본","동경");
    		h.put("중국","베이징");
    		h.put("러시아","모스크바");
    	}
    	
    	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 {
    				break;
    			}
    		}
    	}
    	
    	public void input() {
    		System.out.println("현재 "+h.size()+"개 나라와 수도가 입력되어 있습니다.");
    		while(true) {
    			System.out.print("나라와 수도 입력"+(h.size()+1)+">> ");
    			String nation=sc.next();
    			if(nation.equals("그만")) {
    				break;
    			}
    			String capital=sc.next();
    			if(h.get(nation)!=null) {
    				System.out.println(nation+"은 이미 있습니다!");
    			}
    			else {
    				h.put(nation,capital);
    			}
    		}
    	}
    	public void quizgame() {
    		while(true) {
    			int index=(int)(Math.random()*h.size());
    			
    			Set<String> keys=h.keySet();
    			Object[] arr=keys.toArray();
    			
    			String nation=(String)arr[index];
    			String capital=h.get(nation);
    			System.out.print(nation+"의 수도는? ");
    			String answer=sc.next();
    			
    			if(answer.equals("그만")) {
    				break;
    			}
    			
    			if(answer.equals(capital)) {
    				System.out.println("정답!");
    			}
    			else {
    				System.out.println("아닙니다!");
    			}
    		}
    	}
    }
    
    
    public class p0711 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		quiz q=new quiz();
    		q.run();
    	}
    }
    
    

    [12번]

    import java.util.HashMap;
    import java.util.Scanner;
    import java.util.Set;
    import java.util.Vector;
    
    class quiz{
    	private HashMap<String,String>h =new HashMap<String,String>();
    	Scanner sc=new Scanner(System.in);
    	public quiz() {
    		//h.put으로 초기 17개의 영어단어와 한글 넣기,
    	}
    	
    	public void run() {
    		System.out.println("**** 영어 단어 테스트 프로그램 \"명품영여\" 입니다. ****");
    		while(true) {
    			System.out.print("단어 테스트:1, 단어 삽입:2, 종료:3>> ");
    			int op=sc.nextInt();
    			if(op==1) {
    				quizgame();
    			}
    			else if(op==2) {
    				input();
    			}
    			else {
    				break;
    			}
    		}
    	}
    	
    	public void input() {
    		System.out.println("영어 단어에 그만을 입력하면 입력을 종료합니다.");
    		while(true) {
    			System.out.print("영어 한글 입력 >> ");
    			String eng=sc.next();
    			if(eng.equals("그만")) {
    				break;
    			}			
    			String kor=sc.next();
    			h.put(eng,kor);
    		}
    	}
    	public void quizgame() {
    		while(true) {
    			System.out.println("현재 "+h.size()+"개의 단어가 들어 있습니다. -1을 입력하면 테스트를 종료합니다.");
    			int index=(int)(Math.random()*h.size());
    			
    			Set<String> keys=h.keySet();
    			Object[] arr=keys.toArray();
    			
    			String question=(String)arr[index];
    			String answer=h.get(question);
    			int answeri=(int)(Math.random()*4)+1;
    			System.out.println(question+"?");
    			for(int i=1;i<=4;i++) {
    				if(i==answeri) {
    					System.out.print("("+i+")"+h.get((String)arr[index])+" ");
    					continue;
    				}
    				int randomi=(int)(Math.random()*h.size());
    				if(randomi==index) {
    					i--;
    					continue;
    				}
    				else {
    					System.out.print("("+i+")"+h.get((String)arr[randomi])+" ");
    				}
    			}
    			
    			int reply=sc.nextInt();
    			
    			if(reply==-1) {
    				break;
    			}
    			
    			if(reply==answeri) {
    				System.out.println("Excellent !!");
    			}
    			else {
    				System.out.println("No. !!");
    			}
    		}
    	}
    }
    
    
    public class p0712 {
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		quiz q=new quiz();
    		q.run();
    	}
    }
    
    

     

     

    반응형

    댓글