반응형

문제

Open Challenge를 수정하여 사용자가 단어를 삽입할 수 있도록 기능을 추가하라.

 

출력 예시

**** 영어 단어 테스트 프로그램 "명품영어" 입니다. ****
단어 테스트:1, 단어 삽입:2, 종료:3 >> 1
현재 17개의 단어가 들어 있습니다. -1을 입력하면 테스틑 종료합니다.
eye?
(1)눈 (2)동물 (3)사랑 (4)감정 :>1
Excellent !!
human?
(1)인간 (2)감정 (3)거래 (4)그림 :> 2
No. !!
fault?
(1)오류 (2)감정 (3)사회 (4)조각상 :> 1
Excellent !!
emotion?
(1)그림 (2)사랑 (3)거래 (4)감정 :> ㅁ러미  -잘못입력한경우
숫자를 입력하세요 !!
painting?
(1)거래 (2)눈 (3)애인 (4)그림 :> 4
Excellent !!
animal?
(1)사회 (2)그림 (3)동물 (4)눈 :> -1  -단어 테스트 종료

단어 테스트:1, 단어 삽입:2, 종료:3 >> 2
영어 단어에 그만을 입력하면 입력을 종료합니다.
영어 한글 입력 >> flag 깃발
영어 한글 입력 >>  friend 친구
영어 한글 입력 >>  computer 컴퓨터
영어 한글 입력 >>  imagine 상상
영어 한글 입력 >>  smile 웃음
영어 한글 입력 >>  그만

단어 테스트:1, 단어 삽입:2, 종료:3 >> 1
smile?
(1)상상 (2)사회 (3)웃음 (4)주식 :> 3
Excellent !!
freind?
(1)오류 (2)친구 (3)자기 (4)사진 :> 2
Excellent !!
dall?
(1)컴퓨터 (2)인형 (3)상상 (4) 사랑 :> -1

단어 테스트:1, 단어 삽입:2, 종료:3 >> 3
"명품영어"를 종료합니다.

 

소스 코드

import java.util.*;

class WordTest {
	HashMap<String,String> HM = new HashMap<String,String>();
	ArrayList<Boolean> Check = new ArrayList<Boolean>(); //문제를 냈는지 체크
	WordTest(){
		HM.put("love","사랑");
		HM.put("animal","동물");
		HM.put("emtion","감정");
		HM.put("human","인간");
		HM.put("stock","주식");
		HM.put("trade","거래");
		HM.put("society","사회");
		HM.put("baby","아기");
		HM.put("honey","애인");
		HM.put("dall","인형");
		HM.put("bear","곰");
		HM.put("picture","사진");
		HM.put("painting","그림");
		HM.put("fault","오류");
		HM.put("example","보기");
		HM.put("eye","눈");
		HM.put("statue","조각상");

		Scanner s = new Scanner(System.in);
		int Input;
		
		while(true) {
			System.out.println("**** 영어 단어 테스트 프로그램 \"명품영어\" 입니다. ****");
			System.out.print("단어 테스트: 1, 단어 삽입: 2, 종료: 3>>");
			Input  = s.nextInt();
			s.nextLine();
			switch(Input) {
			case 1:
				for(int i = 0;i<HM.size();i++)
					Check.add(false); //초기화
				System.out.println("현재 "+HM.size()+"개의 단어가 들어 있습니다. -1을 입력하면 테스트를 종료합니다");
				TestRun(s);
				System.out.println();
				break;
			case 2:
				System.out.println("영어 단어에 그만을 입력하면 입력을 종료합니다.");
				AddWord(s);
				System.out.println();
				break;
			case 3:
				System.out.println("\"명품영어\"를 종료합니다.");
				return;
			}
		}
	}
	private void TestRun(Scanner s) {
		Set<String> keys = HM.keySet();
		int TestTime = 0;
		while(true) {
			if(TestTime>=HM.size()) {
				System.out.println("모든 테스트를 진행하였습니다. 종료합니다.");
				return;
			}
			Iterator<String> it = keys.iterator();
			Iterator<String> it2 = keys.iterator();
			int size = HM.size()-1;
			int Random = (int)(Math.random()*size);
			String problem = "";
			if(Check.get(Random) != false)
				continue;
			int k = 0;
			while(it.hasNext()) {
				String temp=it.next();
				if(k == Random)
				{
					problem = temp;
				}
				k++;
			}
			TestTime++;
			System.out.println(TestTime + "번째 실행");
			System.out.println(problem);
			int order[] = new int[4];
			int random1,random2,random3;
			while(true) {
			random1 = (int)(Math.random()*size);
			random2 = (int)(Math.random()*size);
			random3 = (int)(Math.random()*size);
			if(random1 != random2 && random1 != random3 &&
					random1 != Random && random2 != random3 && 
					random2 != Random && random3 != Random)
				break;
			}
			
			order[0] = random1;
			order[1] = random2;
			order[2] = random3;
			order[3] = Random;
			
			Arrays.sort(order);
			int count = 0;
			for(int i =0;i<HM.size();i++)
			{
				String temp = it2.next();
				for(int j = 0;j<4;j++) {
					if(i == order[j])
						System.out.print("("+ ++count + ")" + HM.get(temp) + " ");
				}
			}
			System.out.print(" :> ");
			try {
			int Input = 0;
			Input = s.nextInt();
			if(Input == -1)
				break;
			else if(order[Input-1] == Random)
				System.out.println("Excellent !!");
			else
				System.out.println("NO. !!");
			}
			catch(InputMismatchException e) {
				System.out.println("숫자를 입력하세요 !!");
				s.nextLine();
				continue;
			}
		}
		
		
	}
	private void AddWord(Scanner s) {
		while(true) {
			System.out.print("영어 한글 입력 >> ");
			String eng = s.next();
			if(eng.equals("그만"))
				break;
			String kor = s.next();
			HM.put(eng, kor);
			Check.add(false);
		}
	}
}
public class Main12 {

	public static void main(String[] args) {
		new WordTest();
	}

}

테스트 횟수를 카운트하고 금 범위를 넘어가면 강제로 테스트 종료하여 메인 메뉴로 나가게 하였습니다.

반응형
반응형

문제

나라와 수도 맞추기 게임의 예시는 다음과 같다.

**** 수도 맞추기 게임을 시작합니다 ****
입력:1, 퀴즈: 2, 종료:3 >> 1
현재 9개 나라와 수도가 입력되어 있습니다.
나라와 수도 입력 10 >> 한국 서울
나라와 수도 입력 11 >> 그리스 아테네
그리스는 이미 있습니다!
나라와 수도 입력 11 >> 호주 시드니
나라와 수도 입력 12 >> 이탈리아 로마
나라와 수도 입력 13 >> 그만
입력:1, 퀴즈:2, 종료:3>> 2
호주의 수도는? 시드니
정답!!
독일의 수도는? 하얼빈
아닙니다!!
멕시코의 수도는? 멕시코시티
정답!!
이탈리아의 수도는? 로마
정답!!
한국의 수도는? 서울
정답!!
영국의 수도는? 런던
정답!!
중국의 수도는? 그만
입렵:1, 퀴즈:2, 종료: 3 >> 3
게임을 종료합니다.

 

(1) 나라 이름(country)과 수도(capital)로 구성된 Nation클래스를 작성하고 Vector<Nation>컬렉션을 이용하여 프로그램을 작성하라.

 

소스코드

import java.util.Scanner;
import java.util.Vector;

class Nation {
	String country;
	String capital;
	Nation(String country,String capital){
		this.country = country;
		this.capital = capital;
	}
	public String getcountry() {
		return country;
	}
	public String getcapital() {
		return capital;
	}
}
class CapitalGame{
	Vector<Nation> v = new Vector<Nation>();
	int count = 0;
	public void Menu() {
		System.out.println("**** 수도 맞추기 게임을 시작합니다 ****");
		Scanner s = new Scanner(System.in);
		while(true) {
			System.out.print("입력:1, 퀴즈: 2, 종료:3 >> ");
			int input = s.nextInt();
			switch(input) {
			case 1:
				insert(s);
				break;
			case 2:
				run(s);
				break;
			case 3:
				System.out.println("게임을 종료합니다");
				return;
			default:
				break;
			}
		}
	}
	private void insert(Scanner s) {
		
		while(true) {
		count ++;
		System.out.print("나라와 수도 입력 "+ count +" >>");
		String country = s.next();
		if(country.equals("그만"))
			break;
		if(Checking(country)){
			System.out.println(country + "는 이미 있습니다!");
			continue;
        }
        String capital = s.next();
		v.add(new Nation(country,capital));
		}
	}
	private void run(Scanner s) {
		for(int i =0;i<v.size();i++)
		{
			System.out.print(v.get(i).getcountry() + "의 수도는? ");
			String input = s.next();
			if(v.get(i).getcapital().equals(input))
				System.out.println("정답!!");
			else
				System.out.println("아닙니다!!");
		}
	}
	private boolean Checking(String country) {
		for(int i = 0;i<v.size();i++) {
			if(v.get(i).getcountry().equals(country))
					return true;
		}
		return false;
	}
}
public class Main11 {

	public static void main(String[] args) {
		CapitalGame CG  = new CapitalGame();
		CG.Menu();
	}

}

 

(2) 이 프로그램을 HashMap<String, String>을 이용하여 작성하라. '키' 는 나라 이름이고 '값'은 수도이다.

 

소스 코드

import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

class CapitalGameHash{
	HashMap<String,String> h = new HashMap<String,String>();
	
	
	int count = 0;
	public void Menu() {
		System.out.println("**** 수도 맞추기 게임을 시작합니다 ****");
		Scanner s = new Scanner(System.in);
		while(true) {
			System.out.print("입력:1, 퀴즈: 2, 종료:3 >> ");
			int input = s.nextInt();
			switch(input) {
			case 1:
				insert(s);
				break;
			case 2:
				run(s);
				break;
			case 3:
				System.out.println("게임을 종료합니다");
				return;
			default:
				break;
			}
		}
	}
	private void insert(Scanner s) {
		
		while(true) {
		count ++;
		System.out.print("나라와 수도 입력 "+ count +" >>");
		String country = s.next();
		if(country.equals("그만"))
			break;
		if(Checking(country)) {
			System.out.println(country + "는 이미 있습니다!");
			continue;
		}
		String capital = s.next();
		h.put(country,capital);
		}
	}
	private void run(Scanner s) {
		Set<String> keys = h.keySet();
		
		Iterator<String> it = keys.iterator();
		
		while(it.hasNext()) {
			String temp = it.next();
			System.out.print(temp + "의 수도는? ");
			String input = s.next();
			if(h.get(temp).equals(input))
				System.out.println("정답!!");
			else
				System.out.println("아닙니다!!");
		}
		
	}
	private boolean Checking(String country) {
		for(int i = 0;i<h.size();i++) {
			if(h.containsKey(country))
					return true;
		}
		return false;
	}
}
public class Main11_1 {
	public static void main(String[] args) {
		CapitalGameHash CGH= new CapitalGameHash();
		CGH.Menu();
	}

}

 

반응형
반응형

문제

하나의 학생 정보는 Student 클래스 표현한다. Student 클래스에는 이름, 학과, 학번, 학점 평균을 나타내는 필드가 있다. 여기서 학번을 String 타입으로 선언한다. 키보드에서 학번 정보를 5개 입력받아 학번을 '키' 로 하여 HashMap<String, Student>에 저장하고 학번으로 학생 정보를 검색하여 출력하는 프로그램을 작성하라. 다음과 같은 해시맵을 이용하라.

 

예시 해쉬맵

HashMap<String, Student> dept = new HashMap<String, Student>();

 

소스 코드

import java.util.HashMap;
import java.util.Scanner;

class Student{
	private String name;
	private String department;
	private double Score;
	Student(String name,String department,double Score){
		this.name = name;
		this.department = department;
		this.Score = Score;
	}
	public void Print(){
		System.out.println("학생 이름 : "+name);
		System.out.println("학과 이름 : "+department);
		System.out.println("학점 : "+Score);
	}
}

public class Main9 {
	public static void main(String[] args) {
		HashMap<String, Student> dept = new HashMap<String,Student>();
		Scanner s = new Scanner(System.in);
		System.out.println("학생 5명의 정보를 입력하시오");
		for(int i = 0;i<5;i++)
		{
			System.out.print("학생 이름 : ");
			String name = s.nextLine();
			System.out.print("학과 이름 : ");
			String department = s.nextLine();
			System.out.print("학번 : ");
			String studentID = s.nextLine();
			System.out.print("학점 : ");
			double score = s.nextDouble();
			s.nextLine();
			Student temp = new Student(name,department,score);
			dept.put(studentID,temp);
		}
		
		System.out.print("검색할 학생의 학번을 입력하시오 : ");
		String find = s.nextLine();
		
        System.out.println();
       	
		if(dept.containsKey(find)) {
			System.out.println("학번 : " + find);
			dept.get(find).Print();
		}
		else {
			System.out.println("학생이 존재하지 않습니다.");
		}
		s.close();
	}

}

 

결과

학생 5명의 정보를 입력하시오
학생 이름 : 유관순
학과 이름 : 독립
학번 : 19021216
학점 : 4.5
학생 이름 : 이순신
학과 이름 : 무예
학번 : 15450428
학점 : 4.5
학생 이름 : 세종대왕
학과 이름 : 훈민정음
학번 : 13970515
학점 : 4.5
학생 이름 : 백범 김구
학과 이름 : 독립
학번 : 18760829
학점 : 4.5
학생 이름 : 안중근
학과 이름 : 독립
학번 : 18790902
학점 : 4.5

검색할 학생의 학번을 입력하시오 : 18790902
학번 : 18790902
학생 이름 : 안중근
학과 이름 : 독립
학점 : 4.5
반응형
반응형

문제

키보드로 10개의 나라 이름과 인구를 입력받아 저장하고, 다시 나라 이름을 키보드로부터 입력받아 인구를 출력하는 프로그램을 다음과 같이 해시맵을 이용하여 작성하라.

 

소스코드

import java.util.*;
public class Main3 {

	public static void main(String[] args) {
		HashMap<String,Integer>nations =new HashMap<String,Integer>();
		Scanner scan = new Scanner(System.in);
		
		String Contry;
		int PeopleNumber;
		
		for(int i=0;i<10;i++)
		{
			Contry = scan.next();
				PeopleNumber = scan.nextInt();
			nations.put(Contry,PeopleNumber);
		}
		
		//입력 확인을 위한 출력문
		Set<String>keys = nations.keySet();
		Iterator<String> it = keys.iterator();
		
		while(it.hasNext()) {
			String key = it.next();
			System.out.println("("+key+", "+nations.get(key)+")");
		}
		
		System.out.print("찾으시는 나라를 입력하세요 : ");
		String find = scan.next();
		if(nations.containsKey(find)) {
			System.out.println("찾으시는 나라가 존재합니다.");
			System.out.println("나라 이름 : " + find+", 인구 수 : "+nations.get(find));
		}
		else {
			System.out.println("찾으시는 나라는 Hashmap에 존재하지 않습니다");
		}
		
		
		scan.close();
	}

}

결과

한국 1 미국 2 중국 34 인도 12 일본 0 북극 2 남극 0 독일 2 아르헨티나 3 유럽 2
(독일, 2) (미국, 2) (인도, 12) (일본, 0) (중국, 34) (유럽, 2) (남극, 0) (한국, 1) (북극, 2) (아르헨티나, 3)
찾으시는 나라를 입력하세요 : 한국
찾으시는 나라가 존재합니다.
나라 이름 : 한국, 인구 수 : 1
반응형

+ Recent posts