반응형

문제

앞서 저장한 C:\temp\phone.txt 파일을 읽어 화면에 출력하라.

 

출력 예시

C:\temp\phone.txt를 출력합니다.
황기태 010-5555-7777
이재문 011-3333-4444
김남윤 065-2222-1111

 

소스 코드

import java.io.*;

public class Main2 {
	public static void main(String[] args)
	{
		FileReader fin = null;
		int c;
		try {
			fin = new FileReader("저장된 파일 위치");
			System.out.println("C:\\temp\\phone.txt를 출력합니다.");
			while ((c = fin.read()) != -1) {
				System.out.print((char)c);
			}
			fin.close();;
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}
반응형
반응형

문제

Scanner로 입력받은 이름과 전화번호를 한 줄에 한 사람씩 c:\temp\phone.txt파일에 저장하라. 
"그만"을 입력하면 프로그램을 종료한다.

 

입력 예시

전화번호 입력 프로그램입니다.
이름 전화번호 >> 황기태 010-5555-7777
이름 전화번호 >> 이재문 011-3333-4444
이름 전화번호 >> 김남윤 065-2222-1111
이름 전화번호 >> 그만

 

소스 코드

import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Main1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		FileWriter fout = null;
		System.out.println("전화번호 입력 프로그램입니다.");
		try {
			fout = new FileWriter("파일 위치");
			while(true) {
				System.out.print("이름 전화번호 >> ");
				String line = scanner.nextLine();
				if(line.length()==0 || line.equals("그만"))
					break;
				fout.write(line,0,line.length());
				fout.write("\r\n",0,2);
			}
			fout.close();
		}catch(IOException e) {
			System.out.println("입출력 오류");
		}
		scanner.close();
	}

}

phone.txt 가 아닌 test.txt로 저장하였습니다.

test.txt
0.00MB

반응형
반응형

문제

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

**** 수도 맞추기 게임을 시작합니다 ****
입력: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();
	}

}

 

반응형
반응형

이전 문제까지는 명품JAVA 개정판이였고 이번 문제부터 개정 4판입니다.

 

문제

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

출력 예시

그래픽 에디터 beauty을 실행합니다.
삽입(1), 삭제(2), 모두보기(3), 종료(4) >> 1
Line(1), Rect(2), Circle(3) >> 2
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>1
Line(1), Rect(2), Circle(3) >> 3
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>3
Rect
Circle
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>2
삭제할 도형의 위치 >> 3
삭제할 수 없습니다.
삽입(1), 삭제(2), 모두보기(3), 종료(4)>>4
beauty을 종료합니다.

소스 코드

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

abstract class Shape{
	public Shape() {};
	public abstract String draw(); 
}
class LineTen extends Shape{
	@Override
	public String draw() {
		return "Line";
	}
}
class RectTen extends Shape{
	@Override
	public String draw() {
		return "Rect";
	}
}
class CircleTen extends Shape{
	@Override
	public String draw() {
		return "Circle";
	}
}

class GraphicEditorbeauty{
	Vector<Shape> v = new Vector<Shape>();
	
	public void Menu() {
		Scanner s = new Scanner(System.in);
		System.out.println("그래픽 에디터 beauty을 실행합니다.");
		while(true) {
		System.out.print("삽입(1), 삭제(2), 모두보기(3), 종료(4)>>");
		int input = s.nextInt();
		switch(input) {
		case 1:
			addshape(s);
			break;
		case 2:
			removeshape(s);
			break;
		case 3:
			Print();
			break;
		case 4:
			System.out.println("beauty을 종료합니다.");
			System.exit(0);
			break;
		default:
			break;
		}
		}
	}
	private void Print() {
		for(int i = 0;i<v.size();i++)
		{
			System.out.println(v.get(i).draw());
		}
	}
	private void addshape(Scanner s) {
		System.out.print("Line(1), Rect(2), Circle(3) >> ");
		int input = s.nextInt();
		switch(input) {
		case 1:
			LineTen L = new LineTen();
			v.add(L);
			break;
		case 2:
			RectTen R = new RectTen();
			v.add(R);
			break;
		case 3:
			CircleTen C = new CircleTen();
			v.add(C);
			break;
		default:
			System.out.println("잘못된 입력");
			break;
		}
	}
	private void removeshape(Scanner s) {
		System.out.println("삭제할 도형의 위치 >> ");
		int remove = s.nextInt();
		if(v.size() <= remove) {
			System.out.println("삭제할 수 없습니다.");
		}
		else
			v.remove(remove);
	}
	
}

public class Main10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		GraphicEditorbeauty GE = new GraphicEditorbeauty();
		GE.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
반응형
반응형

문제

다음은 String만 다루는 MyClass 코드이다. MyClass를 제네릭 클래스 MyClass<E>로 일반화하고, 이를 이용하는 main() 메소드를 만들어 프로그램을 완성하라.

문제 소스 코드

public class MyClass {
	private String s;
	public MyClass(String s) {
		this.s = s;
	}
	void setS(String s) {
		this.s = s;
	}
	String getS() {
		return s;
	}
}

 

소스 코드

public class MyClass<E> {
	private E s;
	public MyClass(E s) {
		this.s = s;
	}
	void setS(E s) {
		this.s = s;
	}
	E getS() {
		return s;
	}
	public static void main(String[] args) {
		int n = 10;
		MyClass<Integer> myclass = new MyClass<>(n);
		System.out.println(myclass.getS());
	}

}

 

결과

10
반응형
반응형

문제

아래의 HV 클래스는 해쉬맵을 인자로 받아 벡터를 리턴하는 hashToVector() 메소드를 가지고 있다. 이 메소드는 해쉬맵 내의 '값(value)' 을 모두 Vector<String>에 삽입하여 리턴한다. hashToVector()를 작성하라.

 

문제 소스 코드

import java.util.*;

public class HV {
	public static Vector<String> hashToVector(HashMap<String, String> h){
    
    }
	
	public static void main(String[] args)
	{
		HashMap<String,String> h = new HashMap<String,String>();
		h.put("범죄", "112");
		h.put("화재", "119");
		h.put("전화번호", "114");
		Vector<String> v = HV.hashToVector(h);
		for(int n = 0;n<v.size();n++) {
			System.out.println(v.get(n));
		}
	}
}

 

소스 코드

import java.util.*;

class HV{
	public static Vector<String> hashToVector(HashMap<String,String> h){
		Vector<String> temp = new Vector<String>();
		Set<String> keys = h.keySet();
		for(String s : keys) {
			temp.add(h.get(s));
		}
		return temp;
	}
}
public class Main7 {
	
	public static void main(String[] args)
	{
		HashMap<String,String> h = new HashMap<String,String>();
		h.put("범죄", "112");
		h.put("화재", "119");
		h.put("전화번호", "114");
		Vector<String> v = HV.hashToVector(h);
		for(int n = 0;n<v.size();n++) {
			System.out.println(v.get(n));
		}
	}
}

 

결과

119
112
114
반응형
반응형

문제

main() 함수를 다음과 같이 수행할 수 있도록 GrapgicObject를 상속받는 Rect와 Line을 작성하고, GraphicEditor 클래스에 필요한 메소드 add()와 draw()를 작성하여 완성하라

문제 소스 코드

abstract class GraphicObject{
	int x,y,w,h;
	GraphicObject(int x,int y,int w,int h){
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = h;
	}
	public abstract void view();
}

public class GraphicEditor {
	Vector<GraphicObject> v= new Vector<GraphicObject>();
	
	void add(GraphicObject ob) {
		
	}
	void draw() {
		
	}
	
	public static void main(String[] args) {
		GraphicEditor g = new GraphicEditor();
		g.add(new Rect(2,2,3,4)); // (2,2)에서 3x4짜리 사각형
		g.add(new Line(3,3,8,8)); // (3,3)에서 8x8의 사각형 내의 대각선 직선
		g.add(new Line(2,5,6,6)); // (2,5)에서 6x6의 사각형 내의 대각선 직선
        	g.draw();
	}

}

결과 예시

2, 2 -> 3, 4의 사각형
3, 3 -> 8, 8의 선
2, 5 -> 6, 6의 선

소스코드

import java.util.Iterator;
import java.util.Vector;

abstract class GraphicObject{
	int x,y,w,h;
	GraphicObject(int x,int y,int w,int h){
		this.x = x;
		this.y = y;
		this.w = w;
		this.h = h;
	}
	public abstract void view();
}
class Rect extends GraphicObject{
	Rect(int x,int y,int w,int h){
		super(x,y,w,h);
	}
	
	public void view() {
		System.out.println(x + ", " + y +" -> " + w + ", " + h + "의 사각형");
	}
}

class Line extends GraphicObject{
	Line(int x,int y,int w,int h){
		super(x,y,w,h);
	}
	
	public void view() {
		System.out.println(x + ", " + y +" -> " + w + ", " + h + "의 선");
	}
}
public class GraphicEditor {
	Vector<GraphicObject> v= new Vector<GraphicObject>();
	
	void add(GraphicObject ob) {
		v.add(ob);
	}
	void draw() {
		Iterator<GraphicObject> it = v.iterator();
		while(it.hasNext()) {
			it.next().view();
		}
	}
	
	public static void main(String[] args) {
		GraphicEditor g = new GraphicEditor();
		g.add(new Rect(2,2,3,4)); // (2,2)에서 3x4짜리 사각형
		g.add(new Line(3,3,8,8)); // (3,3)에서 8x8의 사각형 내의 대각선 직선
		g.add(new Line(2,5,6,6)); // (2,5)에서 6x6의 사각형 내의 대각선 직선
		g.draw();
	}

}

결과

2, 2 -> 3, 4의 사각형
3, 3 -> 8, 8의 선
2, 5 -> 6, 6의 선
반응형
반응형

문제

하나의 학생 정보는 Student 클래스로 표현한다. Student 클래스에는 이름, 학과, 학번, 학점 평균을 나타내는 필드가 있다. 키보드로 학생 정보를 5개 입력받아 ArrayList<Student>에 저장한 후에 ArrayList<Student>의 모든 학생 정보를 출력하는 프로그램을 작성하라.

 

소스 코드

import java.util.*;
class Student{
	private String name; // 이름
	private String Department; // 학과
	private int StudentID; // 학번
	private double Score; // 학점
	Student(String name, String Department,int StudentID, double Score){
		this.name = name;
		this.Department = Department;
		this.StudentID = StudentID;
		this.Score = Score;
	}
	public void Print(){
		System.out.println("학생 이름 : "+name);
		System.out.println("학과 이름 : "+Department);
		System.out.println("학번 : "+StudentID);
		System.out.println("학점 : "+Score);
	}
	
}
public class Main5 {
	public static void main(String[] args)
	{
		ArrayList<Student> student = new ArrayList<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("학번 : ");
			int studentID = s.nextInt();
			System.out.print("학점 : ");
			double score = s.nextDouble();
			s.nextLine();
			Student temp = new Student(name,department,studentID,score);
			student.add(temp);
		}
		Iterator<Student> it = student.iterator();
		int i = 1;
		while(it.hasNext()) {
        	System.out.println();
			System.out.println(i+"번 학생");
			it.next().Print();
			i++;
		}
        s.close();
	}
}

결과

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

1번 학생
학생 이름 : 유관순
학과 이름 : 독립
학번 : 19021216
학점 : 4.5

2번 학생
학생 이름 : 이순신
학과 이름 : 무예
학번 : 15450428
학점 : 4.5

3번 학생
학생 이름 : 세종대왕
학과 이름 : 훈민정음
학번 : 13970515
학점 : 4.5

4번 학생
학생 이름 : 백범 김구
학과 이름 : 독립
학번 : 18760829
학점 : 4.5

5번 학생
학생 이름 : 안중근
학과 이름 : 독립
학번 : 18790902
학점 : 4.5
반응형
반응형

문제

다음 프로그램은 ArrayList에 20개의 임의의 실수를 삽입하고 모든 실수를 출력하는 프로그램이다. 모든 실수를 출력하는 부분을 Iterator를 이용하여 수정하라

 

문제 소스

import java.util.ArrayList;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		for(int i = 0;i<20;i++)
		{
			System.out.println(a.get(i));
		}

	}

}

 

소스 코드

(사용할 클래스가 포함된 패키지 선언 방법이 모를 땐, Ctrl + Shift + o(알파벳) 누르시면 자동으로 추가해줍니다.)

import java.util.ArrayList;
import java.util.Iterator;
public class Main4 {
	public static void main(String[] args) {
		ArrayList<Double> a = new ArrayList<Double>();
		for(int i = 0;i<20;i++) {
			double d = Math.random()*100; // 0.0 ~ 100.0 사이의 랜덤한 실수
			a.add(d);
		}
		// 이 부분 수정
		Iterator<Double> it = a.iterator(); 
		// double이 아닌 Double사용해야함 기본 타입 사용 불가
		while(it.hasNext()) { // 값이 있을때 까지 실행
			double n = it.next(); // 다음 값 n에 저장
			System.out.println(n); // 출력
		}

	}

}

결과

21.682354414100423
68.12176249839573
90.18336487034124
20.390411829434807
46.864036416920825
23.31759658352963
28.144614681214698
30.33753351616787
37.83634698945536
14.969898519803415
25.001090784183265
26.670294132217432
21.390460546060865
35.468423285316895
82.38578035008013
65.66836688688392
12.958212033635984
17.656082212719248
83.61235339930406
55.07903459309939

출력결과는 컴파일 할 때마다 달라요.

반응형

+ Recent posts