Download CHAPTER 7 중간점검문제

Document related concepts
no text concepts found
Transcript
CHAPTER 7
중간점검문제
p.142
1. 객체
2. 1960, SIMULA
p.146
1. 데이터, 알고리즘
2. 데이터
3. 클래스를 변경하기가 쉬워진다.
p.148
1. 메시지
2. start(), stop(), speedUp(int s), speedDown(int s), turnLeft(int degree), turnRight(int
degree)
p.157
1. 클래스
2. 변수는 공유되지 않는다. 즉 변수는 각 객체마다 하나씩 생성된다. 하지만 메소드는 공
유된다.
3. 필드, 메소드
4. 도트(.)
5. 필드
6.
class Stock(){
// 필드 정의
public int num;
// 상품번호
public int count;
// 재고수량
// 메소드 정의
public void stockUp(){
count++;
}
public void stockDown(){
count--;
}
}
7.
class Dog(){
// 필드 정의
public String name;
// 이름
public String breed;
public String color;
// 메소드 정의
public void bark(){
...
}
public void bite(){
...
}
public void eat(){
...
}
// 종
// 색깔
}
p.161
1. 기초변수는 int, float, char등의 기초 자료형을 가지는 변수이고, 참조변수는 객체를 참
조할 때 사용되는 변수이다.
2. 두 개의 참조 변수가 하나의 객체를 가리킨다.
3. 참조 변수에 null을 대입한다. 예를 들면 p = null;와 같다.
p.168
1.
2.
3.
4.
5.
기초형, 참조형
new
String
length()
+
Lab
class BankAccount { // 은행 계좌
int balance; // 잔액을 표시하는 변수
void deposit(int amount) { // 저금
balance += amount;
}
void withdraw(int amount) { // 인출
balance -= amount;
}
int getBalance() { // 잔고 반환
return balance;
}
}
public class BankAccountTest {
public static void main(String[] args) {
BankAccount b = new BankAccount();
}
}
(1)
BankAccount b = new BankAccount();
b.balance = 100;
b.withdraw(60);
System.out.println(b.getBalance());
(2)
void addInterest()
{
balance = balance + balance*0.075;
}
(3)
void withdraw(int amount) { // 인출
if( amount < 0 ) return;
balance -= amount;
}
(4) 하나의 소스 파일 안에는 한 개의 public 클래스 만이 있어야 한다. 원칙적으로 public
클래스들은 별도의 소스 파일 안에 정의하여야 한다.
Exercise
1.
class NumberBox {
public int ivalue;
public float fvalue;
}
public class NumberBoxTest {
public static void main(String[] args) {
NumberBox b = new NumberBox();
b.ivalue=10;
b.fvalue=(float)1.2345;
System.out.println(b.ivalue);
System.out.println(b.fvalue);
}
}
2.
상태(속성)
변수
int year
int month
int day
설명
년도
월
일
동작(행동)
메소드 이름
void setDate(int y, int m, int d)
void printDate()
설명
날짜를 설정
날짜를 출력
3.
객체가 생성되지 않았다. new를 이용하여서 객체를 생성해준다.
class Rectangle {
int width, height;
int area() { return width*height; }
}
public class Test {
public static void main(String[] args) {
Rectangle myRect;
myRect = new Rectangle();
myRect.width = 10;
myRect.height = 20;
System.out.println("면적은 " + myRect.area());
}
}
4.
(a)
(b)
(c)
(d)
(e)
생각이현실이 된다
문자열의 길이는7
ABCDEFG
2 + 3 = 5
2 + 3 = 23
Programming
1.
class Rectangle {
int w;
int h;
int area() { return w*h; }
int perimeter() { return 2*(w+h); }
}
public class RectangleTest {
public static void main(String[] args) {
Rectangle myRect;
myRect = new Rectangle();
myRect.w = 10;
myRect.h = 20;
System.out.println("면적은 " + myRect.area());
}
}
2.
class Date {
int year;
int month;
int day;
void print1() {
System.out.println(year + "." + month + "." + day);
}
}
public class DateTest {
public static void main(String[] args) {
Date d;
d = new Date();
d.year = 2012;
d.month = 9;
d.day = 5;
d.print1();
}
}
3.
class ComplexNumber {
int real;
int imag;
void print() {
System.out.println(real + "+ i" + imag);
}
}
public class ComplexNumberTest {
public static void main(String[] args) {
ComplexNumber c;
c = new ComplexNumber();
c.real = 10;
c.imag = 20;
c.print();
}
}
4.
class Movie {
int year;
String title;
void print() {
System.out.println(year + ": " + title);
}
}
public class MovieTest {
public static void main(String[] args) {
Movie m;
m = new Movie();
m.year = 2012;
m.title = "Total Recall";
m.print();
}
}
5.
import java.util.Scanner;
public class StringTest {
public static void main(String[] args) {
String s;
Scanner sc = new Scanner(System.in);
System.out.println("문자열을 입력하시오: ");
s = sc.next();
for(int i=0;i<s.length();i++)
System.out.print(s.charAt(s.length()-1-i));
}
}
6.
import java.util.*;
public class ConVo {
public static void main(String[] args){
String s;
char s2;
int count1 = 0 , count2 = 0;
Scanner scan = new Scanner(System.in);
System.out.print("문자열을 입력하세요 : ");
s = scan.next();
for(int i = 0; i < s.length(); i++){
s2 = s.charAt(i);
if((s2 >= 'A' && s2 <= 'Z') || (s2 >= 'a' && s2 <= 'z')){
if(s2=='a' || s2=='e' || s2 == 'i' || s2 == 'o' || s2 == 'u')
count1++;
else
count2++;
}
}
System.out.println("자음의 개수 : " + count2);
System.out.println("모음의 개수 : " + count1);
}
}
7.
import java.util.*;
public class Password {
public static void main(String[] args){
String s;
String id="abcdef";
Scanner scan = new Scanner(System.in);
System.out.print("아이디를 입력하세요 : ");
s = scan.next();
if( s.equalsIgnoreCase(id) )
System.out.println("로그인이 성공하였습니다");
else
System.out.println("로그인이 실패하였습니다");
}
}
CHAPTER 8
중간점검문제
p.179
1. 크게 나누면 기초형 변수와 참조형 변수가 존재한다.
2. 잘못된 값이 저장되는 것은 사전에 체크할 수 있고 또 필요할 때마다 값을 다시 계산하
여서 반환할 수도 있다.
3. 필드는 클래스 안에 선언되는 변수이다. 지역 변수는 메소드 안에 선언되어서 메소드 안
에서만 사용되는 변수이다.
p.185
1. 중복 메소드(overloading method)
2. 값을 반환하지 않는 메소드를 나타낸다.
3.
public void printMyName() {
String name;
System.out.println("이름을 입력하시오 :");
Scanner scan = new Scanner(System.in);
name = scan.nextLine();
System.out.println(name);
}
p.187
TV
-isOn : bool
-channel: int
+turnOn()
+turnOff()
1. +setChannel(int)
+getChannel(); int
Lab
1.
(1)
class Box {
// 필드 정의
int width;
int length;
int height;
// 메소드 정의
}
(2)
class Box {
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
// 필드 정의
int width;
int length;
int height;
// 메소드 정의
}
(3)
public int getVolume() {
return width*length*height;
}
(4)
public void print() {
System.out.println("가로:" + width);
System.out.println("세로:" + width);
System.out.println("높이:" + width);
}
(5)
public class BoxTest {
public static void main(String[] args) {
Box box1;
}
}
(6)
box1 = new Box();
(7)
box1.setWidth(100);
box1.setLength(100);
box1.setHeight(100);
(8)
System.out.println(box1.getVolume());
1000000
(9)
Box box2;
box2 = new Box();
box2.setWidth(200);
box2.setLength(200);
box2.setHeight(200);
(10)
box1 = box2;
box1.print();
1000000
가로:200
세로:200
높이:200
Exercise
1. 설정자에서 매개 변수를 통하여 잘못된 값이 넘어오는 경우, 이를 사전에 차단할 수 있
다. 필요할 때마다 필드값을 계산하여 반환할 수 있다. 접근자만을 제공하면 자동적으로 읽
기만 가능한 필드를 만들 수 있다.
2.
class Television {
private String model;
void setModel(String b) { // 설정자
model = b;
}
String getModel() { // void->String
return model;
}
}
public class TelevisionTest {
public static void main(String[] args) {
Television t = new Television(); // ()을 붙여주어야 함!
t.setModel("STV-101");
String b = t.getModel(); // 객체 참조 변수 t를 적어주어야 함.
}
}
3.
(1)
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
Movie
-title : String
-director : String
-actor : String
+getTitle()
+getDirector()
+getActor()
+setTitle()
(2) +setDirector()
+setAcotr()
(3)
public class Movie
{
private String title, director, actors;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActors() {
return actors;
}
public void setActors(String actors) {
this.actors = actors;
}
}
(4)
Movie m = new Movie();
m.setTitle("Transformer");
4.
(1) 은행, 정기 예금 계좌, 보통 예금 계좌, 고객
(2) SavingsAccount, CheckingAccount, Customer
(3)
Account: 계좌 번호, 소유자 이름, 잔액, deposit(), withdraw()
SavingsAccount extends Account: 이자율, 이자계산()
CheckingAccount extends Account: 카드번호(수표번호), 부도여부
Customer: 이름, 주소, 소유한 계좌번호
class Account {
String AccNumber;
String ownerName;
int balance;
void deposit(int amount) {
balance += amount;
}
void withdraw(int amount) {
if (balance > amount)
balance -= amount;
}
}
class CheckingAccount extends Account {
String cardNumber;
boolean status;
}
Programming
1.
Circle
-r : double
-cx : double
-cy : double
+area()
+setR()
+setCx()
+setCy()
+getR()
+getCx()
+getCy()
class Circle {
double r;
double cx;
double cy;
public double area() {
return 3.141592*r*r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getCx() {
return cx;
}
public void setCx(double cx) {
this.cx = cx;
}
public double getCy() {
return cy;
}
public void setCy(double cy) {
this.cy = cy;
}
}
public class CircleTest {
public static void main(String[] args){
Circle c = new Circle();
c.setR(10.0);
System.out.println(c.area());
}
}
2.
class Book {
private String title, author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
public class BookTest {
public static void main(String[] args){
Book b = new Book();
b.setTitle("data structure");
b.setAuthor("홍길동");
}
}
3.
class Dice {
private int face;
int roll() {
int face = (int)(Math.random() * 6) + 1;
return face;
}
}
public class DiceTest{
public static void main(String[] args){
Dice dice = new Dice();
System.out.println("주사위 숫자 : " + dice.roll());
}
}
4.
class Point {
int x, y;
public void set(int x, int y)
{
this.x = x;
this.y = y;
}
public void print()
{
System.out.println("("+x+","+y+")");
}
}
public class PointTest {
public static void main(String[] args){
Point p = new Point();
p.set(10, 10);
p.print();
}
}
5.
class Employee{
private String name;
private int tel;
private int sal;
public void setName(String n){
name = n;
}
public void setTel(int t){
tel = t;
}
public void setSal(int s){
sal = s;
}
public String getName(){
return name;
}
public int getTel(){
return tel;
}
public int getSal(){
return sal;
}
}
public class EmployeeTest {
public static void main(String[] args){
Employee em = new Employee();
}
}
6.
class BankAccount{
int accountNumber;
String owner;
int balance;
void deposit(int amount){
balance += amount;
}
void withdraw(int amount){
balance -= amount;
}
public String toString(){
return "현재 잔액은 " + balance + "입니다.";
}
public int transfer(int amount, BankAccount otherAccount){
otherAccount.deposit(amount);
return (balance-amount);
}
}
public class BankAccountTest {
public static void main(String[] args){
BankAccount myAccount1 = new BankAccount();
BankAccount myAccount2 = new BankAccount();
myAccount1.deposit(10000);
System.out.println("myAccount1 : " +myAccount1);
myAccount1.withdraw(8000);
System.out.println("myAccount1 : " + myAccount1);
System.out.println("myAccount2 : " + myAccount2);
int b = myAccount1.transfer(1000, myAccount2);
myAccount1.withdraw(b);
System.out.println("myAccount1 : " + myAccount1);
System.out.println("myAccount2 : " + myAccount2);
}
}
7.
class Average {
public int getAverage(int a, int b){
return (a+b)/2;
}
public int getAverage(int a, int b, int c){
return (a+b+c)/2;
}
}
public class AverageTest {
public static void main(String[] args){
Average a = new Average();
System.out.println(a.getAverage(10, 20));
System.out.println(a.getAverage(10, 20, 30));
}
}
78.5398
31.41592
CHAPTER 9
중간점검문제
p.205
1. MyClass
2. 생성자는 반환형이 없다.
3. 기존 생성자 호출
p.210
1. 정적 변수는 클래스의 모든 객체들에 의해 공유될때 사용하는것이 좋다.
2. 정적 변수와 정적 메소드는 객체를 생성할 필요가 없고 매개 변수를 통하여 전달된 값만
있으면 되므로 클래스 이름을 통하여 접근한다.
3. main()메소드도 정적 메소드이기 때문
p.213
1. 필드를 다른 클래스가 직접 사용하지 못하게 하기 위해서
2. 디폴트로 package가 된다. 즉 같은 패키지에 속하는 클래스들은 자유롭게 사용할 수 있
다.
p.214
1. 자기 자신을 참조하는데 사용된다.
2. 자신의 생성자 호출한다.
p.217
1. 사용관계는 하나의 클래스가 다른 클래스를 사용하는 것이고, 집합관계는 하나의 클래스
가 다른 클래스를 포함하는 것이다.
Lab
1.
public class Circle {
private double radius;
static final double PI=3.141592; // PI라는 이름으로 3.141592로 초기화된 정적 상
수
}
(1)
public Circle(double r){
radius = r;
}
(2)
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
(3)
private double square(double value)
{
return value*value;
}
(4)
public double getArea()
{
return square(radius)*PI;
}
(5)
public double getPerimeter()
{
return 2.0*PI*radius;
}
(6)
public static double getPI()
{
return PI;
}
(7) square() 함수는 정적 함수가 아니라서 main()에서 호출하면 오류가 발생한다.
(8) getPI() 함수는 정적 함수이므로 main()에서 호출할 수 있다.
(9)
class Circle {
private double radius;
static final double PI=3.141592; // PI라는 이름으로 3.141592로 초기화된 정적
상수
public Circle(double r){
radius = r;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
private double square(double value)
{
return value*value;
}
public double getArea()
{
return square(radius)*PI;
}
public double getPerimeter()
{
return 2.0*PI*radius;
}
public static double getPI()
{
return PI;
}
}
public class CircleTest {
public static void main(String args[]) {
Circle c = new Circle(5.0); // 객체 생성, 생성자 호출시 반지름을 5.0으로 설정
System.out.println(c.getArea());// 원의 면적 계산하여 출력
System.out.println(c.getPerimeter());// 원의 둘레 계산하여 출력
}
}
Exercise
1.
(1)
(2)
(3)
(4)
객체가 생성될 때에 필드에게 초기값을 제공하고 필요한 초기화 절차를 실행
매개변수의 자료형이나 매개변수 개수로 구별되어 호출
자기 자신을 참조
정적변수는 하나의 클래스에 하나만 존재하여 그 클래스의 모든 객체들에 의해 공유되
지만 인스턴스 변수는 각 인스턴스마다 별도로 생성된다.
(5) 객체의 참조값이 전달된다.
(6) 정적 메소드는 객체가 생성되지 않은 상태에서 호출되는 메소드이므로 객체 안에서 존
재하는 인스턴스 변수들은 사용할 수 없다.
2.
(1) 생성자 Point()는 값을 반환하지 않는다 따라서 void를 삭제한다.
(2) 메소드의 반환형이 다르다고 해서 메소드를 중복시킬 수 있는 것은 아니다.
class MyMath {
public int getRandom1(){
return (int)Math.random();
}
public double getRandom(){
return Math.random();
}
}
(3) 정적 메소드 getStringName()에서 인스턴스 메소드 getName()을 호출할 수 없다.
class MyClass{
private static String getName(){
return "Myclass";
}
public static String getClassName(){
return getName();
}
}
3.
(1)
public class Cube {
private double side;
// 정육면체의 한변
public Cube()
{
side = 0;
}
public double getSide() {
return side;
}
public double getVolume() {
return side*side*side;
}
}
(2)
public class Cube {
private double side;
// 정육면체의 한변
public Cube()
{
side = 0;
}
public Cube(double side)
{
this.side = side;
}
public double getSide() {
return side;
}
public double getVolume() {
return side*side*side;
}
}
4.
class MyMetric {
private static double distance;
public static double kiloToMile(double d){
distance = d / 1.6093;
return distance;
}
public static void miletoKilo(double d){
distance = d * 1.6093;
}
}
public class MyMetricTest{
public static void main(String args[]){
double d = MyMetric.kiloToMile(1);
System.out.println(d);
}
}
5.
s_instance가 null일 때만 객체를 생성하고 이미 객체가 생성되어 있으면 단순히 객체의 참
조값을 반환한다.
class Single {
private static Single s_instance;
public static Single getInstance() {
if (s_instance == null) {
s_instance = new Single();
}
return s_instance;
}
}
Programming
1.
Dog
-name : String
-breed : String
-age : int
+getName()
+getBreed()
+getAge()
+setName()
+setBreed()
+setAge()
public class Dog {
private String name;
private String breed;
private int age;
public Dog(String name, int age){
this.name = name;
this.age = age;
}
public Dog(String name, String breed, int age){
this.name = name;
this.breed = breed;
this.age = age;
}
public String getName()
{
return name;
}
public String getBreed()
{
return breed;
}
public int getAge()
{
return age;
}
public void setName(String n)
{
name = n;
}
public void setBreed(String b)
{
breed = b;
}
public void setAge(int a)
{
age = a;
}
}
2.
class Plane{
private int num, p_num;
private String model;
private static int planes;
public void setNum(int n){
num = n;
}
public void setPnum(int pn){
p_num = pn;
}
public void setModel(String m){
model = m;
}
public int getNum(){
return num;
}
public int getPnum(){
return p_num;
}
public String getModel(){
return model;
}
public static void setPlanes(int p){
planes = p;
}
public static int getPlanes(){
return planes;
}
public Plane(){ }
public Plane(int n, String m, int pn){
num = n;
p_num = pn;
model = m;
}
public Plane(int n, String m){
num = n;
model = m;
}
public String toString(){
return "식별번호 :" + getNum() + "모델 : " + getModel() + "승객수 : " +
getPnum();
}
}
public class PlaneTest {
public static void main(String[] args){
Plane plane1 = new Plane(1, "aa", 200);
Plane plane2 = new Plane(2, "bb");
Plane plane3 = new Plane();
plane1.setPlanes(0);
plane1.getPlanes();
plane3.setNum(3);
plane3.setModel("cc");
plane3.setPnum(150);
}
}
3.
public class Box {
private int width, length, height;
private boolean empty = false;
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getLength() {
return length;
}
public void setLength(int length) {
this.length = length;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public boolean isEmpty() {
return empty;
}
public void setEmpty(boolean empty) {
this.empty = empty;
}
public Box()
{
width = 0;
length = 0;
height = 0;
empty = true;
}
public Box(int w, int l, int h){
width = w;
length = l;
height = h;
empty = true;
}
}
4.
public class Movie {
private String title;
private String direction;
private String company;
public Movie(){}
public Movie(String t, String d, String c){
title = t;
direction = d;
company = c;
}
}
5.
public class BankAccount {
private String ownerName;
private int accountNumber;
private int balance;
private double rate;
public String getOwnerName() {
return ownerName;
}
public void setOwnerName(String ownerName) {
this.ownerName = ownerName;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public double getRate() {
return rate;
}
public void setRate(double rate) {
this.rate = rate;
}
public BankAccount()
{
}
public BankAccount(String n, int a, int b, double r){
ownerName = n;
accountNumber = a;
balance = b;
rate = r;
}
}
CHAPTER 10
중간점검문제
p.230
1. int[] array = new int[100];
2. 0에서 9 사이의 정수
3. 예외(오류)가 발생한다.
4. double[] array = { 1.2, 3.1, 6.7 };
5.
for(i=0;i<array.length;i++){
array[i] = 2 * array[i];
}
6.
Scanner scan=new Scanner(System.in);
System.out.println(“배열의 크기: ”);
int size = scan.nextInt();
int[] array = int[size];
7. for-each와 전통적인 for 루프를 비교하라.
for-each루프는 배열의 크기에 신경쓰지 않아도 되고 인덱스 변수를 생성할 필요없이 배열
의 첫 번째 원소부터 마지막 원소의 값을 꺼내서 처리하는 경우에 사용한다. 하지만 역순으
로 배열 원소를 처리하거나 일부 원소만 처리하는 경우는 for루프를 사용한다.
전통적인 for루프를 사용하면 배열의 원소를 변경할 수 있지만 for-each보다 불편할 수 있
다. 뒤에서 학습하는 컬렉션에서는 for-each구조가 무척 편리하다.
8. 배열의 크기가 동일하다고 가정하자.
for(i=0;i<length;i++){
array2[i] = array1[i];
}
9. 배열의 참조값이 전달된다.
10. 배열 원소는 값이 전달되고 배열은 참조가 전달된다.
p.232
1.
BankAccount[] bank = new BankAccount[3];
for(int i =0; i < bank.lengh; i++)
bank[i] = new BankAccount();
2. 참조값이 전달된다.
p.234
1. Book[][] library = new Book[8][100];
2. 2차원 배열 객체를 가리키는 참조값이 전달된다.
Lab
1.
class
Employee {
String name; // 직원의 이름
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String address; // 주소
int salary; // 연봉
String phone; // 전화 번호
}
2.
import java.util.Scanner;
class Employee {
String name; // 직원의 이름
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String address; // 주소
int salary; // 연봉
String phone; // 전화 번호
}
public class EmployeeTest {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
// 크기가 3인 Employee의 배열 employees을 생성한다.
Employee[] employees = new Employee[3];
// 3명의 사원 정보를 받아서 각각 Employee 객체를 생성한 후에 배열에
추가하여 본다. 반복 루프를 사용한다.
for (int i = 0; i < employees.length; i++)
employees[i] = new Employee();
for (int i = 0; i < employees.length; i++) {
System.out.println("이름: ");
employees[i].name = scan.next();
System.out.println("주소: ");
employees[i].address = scan.next();
}
// employees 배열에 저장된 모든 데이터를 출력한다. 반복 루프를 사용
한다.
for (int i = 0; i < employees.length; i++) {
System.out.println("이름: " + employees[i].name);
System.out.println("주소: " + employees[i].address);
}
}
}
Exercise
1.
(1) int[] studentNumbers = new int[30];
(2) double[] values = {1.2, 3.3, 6.7};
2.
(1) int[] numbers = new int[100];
(2) double[] rainfalls = new double[100];
3.
(1) 0부터 4까지
(2) 실시간 오류 발생
4.
for(int i = 0; i < values.length; i++){
values[i] = 0;
5.
int[] a = {1, 2, 3, 4, 5};
int[] b = new int[5];
for(int i = 0; i < a.length; i++)
b[i] = a[i];
6.
String[] employees = new String[10];
String name = "홍길동";
employees[0] = name;
name = null;
배열의 원소 중에서 0번째를 제외하고 나머지 원소들은 초기화가 안 되었다. 따라서 9개의
null 참조가 배열 employees[] 안에 존재한다.
Programming
1.
import java.util.Scanner;
class Theater {
int[] seats;
int size;
public Theater(int size)
{
this.size=size;
seats = new int[size];
}
public void print()
{
System.out.println("----------------------------");
for(int i=0; i<size; i++)
System.out.print(i+" ");
System.out.println("\n----------------------------");
for(int i=0; i<size; i++)
System.out.print(seats[i]+" ");
System.out.println("\n----------------------------");
}
public void reserve()
{
System.out.println("몇번째 좌석을 예약하시겠습니까?");
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
if( seats[s] == 0 ){
seats[s] = 1;
System.out.println("예약되었습니다.");
}
}
}
public class TheaterTest {
public static void main(String args[]) {
Theater t = new Theater(10);
t.print();
t.reserve();
t.print();
}
}
2.
import java.util.Scanner;
class Histogram {
int[] freq;
int size;
public Histogram(int size)
{
this.size = size;
freq = new int[size];
}
public void print()
{
for(int i=0; i<size; i++){
System.out.print((i*10+1)+"-"+(i+1)*10);
for(int k=0; k<freq[i]; k++)
System.out.print("*");
System.out.println("");
}
}
public void input()
{
System.out.println("점수를 입력하시오");
Scanner scan = new Scanner(System.in);
int s = scan.nextInt();
if( s!= 0 )
freq[(s-1)/10]++;
else
freq[0]++;
}
}
public class HistogramTest {
public static void main(String args[]) {
Histogram t = new Histogram(10);
for(int i=0;i<10;i++)
t.input();
t.print();
}
}
3.
import java.util.Scanner;
public class ScoreTest {
static int[] num = new int[5];
static int sum =0;
static double avg;
public static void main(String[] args){
Scanner s = new Scanner(System.in);
for(int i=0; i<5; i++){
System.out.println("성적을 입력하세요");
num[i] = s.nextInt();
}
getTotal();
getAverage();
}
private static void getAverage() {
avg = sum / 5.0;
System.out.println("평균 : "+avg);
}
private static void getTotal() {
for(int i =0; i < 5; i++)
sum += num[i];
System.out.println("합계 : "+sum);
}
}
4.
import java.util.Scanner;
class Hexa2Bin {
String[] hexa2bin = {"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};
public void print(String s)
{
for(int i=0;i<s.length();i++){
char c = s.charAt(i);
int index = 0;
if( c >='0' && c <='9') index = (c - '0');
if( c >='a' && c <='f') index = 10 + (c - 'a');
System.out.print(hexa2bin[index]+" ");
}
System.out.print("");
}
}
public class HistogramTest {
public static void main(String args[]) {
Hexa2Bin t = new Hexa2Bin();
t.print("1abc");
}
}
CHAPTER 11
중간점검문제
p.230
1. 컴퓨터가 수퍼클래스, 데스크탑, 노트북, 태블릿이 모두 서브클래스가 된다.
컴퓨터
데스크탑
노트북
태블릿
2. 상속은 코드를 재사용하며 코드의 중복을 줄인다.
p.246
1. sleep()과 eat()가 수퍼클래스에서만 정의되므로 코드가 간결해진다.
2.
class Box {
int width, length, height;
public int calVolume()
{
return width*height*height;
}
}
class ColorBox extends Box {
String color;
}
Lab
import java.util.Scanner;
class Human {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Human [name=" + name + ", age=" + age + "]";
}
public String getProfession() {
return "unknown";
}
public Human(String name, int age) {
super();
this.name = name;
this.age = age;
}
}
class Student extends Human {
@Override
public String toString() {
return super.toString() + "Student [major=" + major + "]";
}
public String getProfession() {
return "student";
}
String major;
public Student(String name, int age, String major) {
super(name, age);
this.major=major;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
public class StudentTest {
public static void main(String args[]) {
Student s1 = new Student("명진", 21, "컴퓨터");
Student s2 = new Student("미현", 22, "경영");
Student s3 = new Student("용준", 24, "경제");
}
}
Exercise
1.
(1) Student, GraduateStudent
(2)
Student
-number: int
+name : String
GraduateStudent
+lab : String
(3)
class Student {
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private int number;
public String name;
}
public class GraduateStudent extends Student {
public String getLab() {
return lab;
}
public void setLab(String lab) {
this.lab = lab;
}
public String lab;
}
(4)
class Student {
public Student(int number, String name) {
super();
this.number = number;
this.name = name;
}
...
private int number;
public String name;
}
public class GraduateStudent extends Student {
public GraduateStudent(int number, String name, String lab) {
super(number, name);
this.lab = lab;
}
...
public String lab;
}
(5) (1) private 멤버는 접근할 수 없다.
2. (1) methodTwo()
(2) methodFour()
(3) methodOne()과 methodThree()는 컴파일 오류를 발생한다. 인스턴스 메소드를 정적 메
소드로 재정의할 수는 없다. 그 반대도 마찬가지이다.
3.
class Bike
{
protected int gear;
public int speed;
}
public class MountainBike extends Bike
{
public int seatHeight;
public MountainBike(int g)
{
super();
gear=g;
}
}
4.
동물입니다:Brave
사자입니다.
동물입니다:UNKNOWN
사자입니다.
Programming
1.
class Circle {
double radius;
String color;
public Circle(double radius) {
super();
this.radius = radius;
}
public Circle() {
super();
this.radius = 0;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return 3.141592 * radius * radius;
}
}
class Cylinder extends Circle {
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public Cylinder() {
super(0);
}
public Cylinder(double radius) {
super(radius);
}
public double getVolume() {
return super.getArea() * height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
double height;
}
public class TestCylinder {
public static void main(String[] args) {
Cylinder obj1 = new Cylinder();
System.out.println(obj1.getHeight());
System.out.println(obj1.getRadius());
Cylinder obj2 = new Cylinder(5.0, 3.0);
System.out.println(obj2.getHeight());
System.out.println(obj2.getRadius());
}
}
2.
class Person {
public Person(String name, String address) {
super();
this.name = name;
this.address = address;
}
public Person(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
String name;
String address;
String phone;
}
class Customer extends Person {
public Customer(String name, String address, int customerNumber, int mileage) {
super(name, address);
this.customerNumber = customerNumber;
this.mileage = mileage;
}
public Customer(String name, String address, String phone) {
super(name, address, phone);
}
int customerNumber;
int mileage;
}
public class Test {
public static void main(String[] args) {
...
}
}
3.
class Shape {
protected int x, y;
protected int w, h;
public double getArea() {
return 0;
}
public double getPerimeter() {
return 0;
}
}
class Triangle extends Shape {
int a, b, c;
public Triangle(int a, int b, int c) {
super();
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
return 2.0 * w * h;
}
@Override
public double getPerimeter() {
return a + b + c;
}
}
public class Test {
public static void main(String[] args) {
...
}
}
4.
Book
-title
-pages
-writer
+getTitle()
+setTitle()
+getPages()
+setPages()
+getWriter()
+setWriter()
+toString
Magazine
-date
<-
+getDate()
+setDate()
+main()
class Book{
private String title;
private int pages;
private String writer;
public Book(String title,int pages,String writer)
{
this.title=title;
this.pages=pages;
this.writer=writer;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title=title;
}
public int getPages(){
return pages;
}
public void setPages(int pages){
this.pages=pages;
}
public String getWriter(){
return writer;
}
public void setWriter(String writer){
this.writer=writer;
}
public String toString(){
return "책 이름 : "+title+"\n페이지 수 : "+pages+"\n저자 : "+writer;
}
}
public class Magazine extends Book{
private String date;
public Magazine(String title,int pages,String writer,String date)
{
super(title,pages,writer);
this.date=date;
}
public String toString(){
return super.toString()+"\n발매일 :"+date;
}
public static void main(String[] args) {
Magazine 잡지A = new Magazine("잡지A",10,"기자A","2010년 2월 25일");
Magazine 잡지B = new Magazine("잡지B",20,"기자B","2010년 3월 8일");
System.out.println(잡지A.toString());
System.out.println(잡지B.toString());
}
}
5. 음식을 나타내는 Food클래스를 상속받아 멜론을 나타내는 Melon 클래스를 작성.
Food 클래스는 칼로리, 가격, 중량 등의 정보를 가진다.
Melon 클래스는 추가로 경작 농원 정보를 가진다. (UML을 그린다.)
Melon_Test
+main() : void
Melon
->Food
-info : string
+getInfo() : string
+setInfo() : void
+toString(): string
class Food{
private int cal;
private int cost;
private int kg;
Food
-cal : int
-cost : int
-kg : int
+getCal() : int
+getCost() : int
+getKg() : int
+setCal() : void
+setCost() : void
+setKg() :void
//필드 데이터 정의
public Food(int cal, int cost, int kg){ //생성자 매개변수 존재
this.cal = cal;
this.cost = cost;
this.kg = kg;
}
public Food(){
//생성자
this.cal = 0;
this.cost = 0;
this.kg = 0;
}
public void setCal(int cal){
this.cal = cal;
}
public void setCost(int cost){
this.cost = cost; }
public void setKg(int kg){
//설정자.
this.kg = kg;
public int getCal(){
return cal;
public int getCost(){
return cost;
public int getKg(){
return kg;
}
//접근자.
}
}
}
}
class Melon extends Food{
private String info;
//melon 클래스 작성 Food 상속
//필드 정의
//Food 상속 생성자 작성
public Melon(int cal, int cost, int kg,String info) {
super(cal, cost, kg);
this.info = info;
}
public Melon(){
super();
info = "NULL";}
public void setInfo(String info){
this.info = info;
}
public String getInfo(){
return info;
}
//Food 생성자 호출
//설정자.
//접근자.
public String toString(){
return "Melon의 정보\n칼로리 : "+this.getCal()+"\n가격 : "+
this.getCost()+"\n중량 : "+this.getKg()+"\n정보"+this.getInfo();
}
}
public class Melon_Test {
public static void main(String[] args) {
Melon m1 = new Melon(124,21,2,"jjh_fram");
Melon m2 = new Melon(1,1,1,"0");
m2.setCal(100);
m2.setCost(210);
m2.setKg(21);
m2.setInfo("jjh2_Test");
System.out.println(m1+"\n");
System.out.println(m2);
}
}
6.
class Phone {
public Phone(String maker, int price, int type) {
super();
this.maker = maker;
this.price = price;
this.type = type;
}
public String getMaker() {
return maker;
}
public void setMaker(String maker) {
this.maker = maker;
}
//드라이버 클래스 작성
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
protected String maker;
protected int price;
protected int type;
}
class SmartPhone extends Phone {
public String getOs() {
return os;
}
public SmartPhone(String maker, int price, int type, String os,
String version, int memory, boolean hasCamera,
hasBluetooth) {
super(maker, price, type);
this.os = os;
this.version = version;
this.memory = memory;
this.hasCamera = hasCamera;
this.hasBluetooth = hasBluetooth;
}
public void setOs(String os) {
this.os = os;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getMemory() {
return memory;
}
public void setMemory(int memory) {
this.memory = memory;
}
public boolean isHasCamera() {
return hasCamera;
}
public void setHasCamera(boolean hasCamera) {
this.hasCamera = hasCamera;
}
public boolean isHasBluetooth() {
return hasBluetooth;
boolean
}
public void setHasBluetooth(boolean hasBluetooth) {
this.hasBluetooth = hasBluetooth;
}
private String os;
private String version;
private int memory;
private boolean hasCamera;
private boolean hasBluetooth;
}
public class Test {
public static void main(String[] args) {
...
}
}
7.
class Student{
private
private
private
private
private
String name;
int number;
String major;
int grade;
int next_point;
//Student 클래스 정의
//필드데이터 정의
//이름,학번,전공,학년,학점
//생성자 정의
public Student(String name,int number,String major,int grade,int next_point){
this.name = name;
//매개 변수 와 필드 데이터 이름이
같기에
this.number = number;
this.major = major;
this.grade = grade;
this.next_point = next_point;
//this.사용 자신의 클래스 변수를 참조
}
public Student(){
name = null;
number = 0;
major = null;
grade = 0;
next_point = 0;
}
public String getName(){
return name;
}
//접근자를 설정 한다.
//외부서 접근자를 통해 해당 데이터
저장
public int getNumber(){
return number; }
public String getMajor(){
return major;
}
public int getGrade(){
return grade;
}
public int getNext_point(){
return next_point;
}
public void setName(String name){
this.name = name;
}
//설정자 정의
//설정자를 통해 클래스 데이터 변경가
능
public void setNumber(int number){
this.number = number; }
public void setMajor(String major){
this.major = major;
}
public void setGrade(int grade){
this.grade = grade;
}
public void setNext_point(int next_point){
this.next_point = next_point;
}
public String toString(){
//toString 재 정의한다. 클래스 정보를
출력
return "이름 :"+name+" 학번 :"+number+" 학과 :"+major+" 학년 :"+
grade+" 이수학점 :"+next_point; }
}
class underGraduate extends Student{
private String club;
//학부생 클레스 정의 Stduent 로부터 상속받음.
//필드데이터 정의 "동아리 이름"
//생성자 정의
public underGraduate(String name, int number, String major, int grade,
int nextPoint, String club) {
super(name, number, major, grade, nextPoint);
//super 통해 부모 클래스 생성자 호출
this.club = club; }
public underGraduate(){
super();
club = null;
}
public void setClub(String club){
this.club = club; }
public String getClub(){
return club;
}
//생성자 설정
//접근자 설정
//toString 재정의한다. 학부생 클래스 정보 출력
public String toString(){
return "이름 :"+getName()+"/ 학번 :"+getNumber()+"/ 학과 :"+getMajor()+
"/ 학년 :"+getGrade()+"/ 이수학점 :"+getNext_point() + "/ 소속 동아리
:"+club;
}
}
class Graduate extends Student{
private String assistant ;
private boolean scholarship;
//교육조교
//장학금여부
//생성자를 정의 한다.
public Graduate(String name, int number, String major, int grade,
int nextPoint,String assistant, int scholarship) {
super(name, number, major, grade, nextPoint);
//super 사용 부모 클래스 생성자 호출
this.assistant = assistant;
this.scholarship = ((scholarship == 1)? true:false); //입력값을 확인
}
//1일경우 true 그외일 경우 false 저장
public Graduate(){
super();
assistant = null;
scholarship = false;
}
public void setAssistant(String assistant){
this.assistant = assistant; }
public void setScholarship(boolean scholarship){
this.scholarship = scholarship;
}
//설정자 정의
public String getAssistant(){
return assistant; }
public boolean getScholarship(){
return scholarship;
//접근자 정의
}
//toString 재 정의 대학원생 클래스의 정보를 출력
public String toString(){
return "이름 :"+getName()+"/ 학번 :"+getNumber()+"/ 학과 :"+getMajor()+
"/ 학년 :"+getGrade()+"/ 이수학점 :"+getNext_point() + "/ 조교 유형
:"+assistant+"/ 장학금 여부 :"+((scholarship == true)? "받음":"못받음");
}
}
public class student_Test {
public static void main(String[] args) {
underGraduate ug1 = new underGraduate("갑",1000,"컴공",3,84,"날자날어
");
Graduate g1 = new Graduate("을", 100, "전자공학", 2, 51,"교육 조교",0);
Graduate g2 = new Graduate("병", 100, "세포생물", 2, 61,"연구 조교",1);
//대학원생 객체를 두개 생성 g1,g2를 통해 참조
가능.
System.out.println(ug1); //ug1이 가르키는 객체 정보를
출력(toString 호
출)
ug1.setClub("돌고 돌아"); //ug1이 가르키는 객체 클럽설정자 호출, 값 변
경
ug1.setNext_point(87);
//ug1이 가르키는 객체 학점설정자 호출, 데이터
변경
System.out.println(ug1); //ug1이 가르키를 객체 정보를 출력
System.out.println(g1);
//g1이 가르키를 객체 정보를 출력
g2.setGrade(3);
//g2가 가르키는 객체 학년설정자를 호출, 값 변
경
g2.setNumber(102);
//g2가 가르키는 객체 학번설정자를 호출, 값
변경
System.out.println(g2);
}
}
//g2의 객체 정보를 다시 출력
CHAPTER 12
중간점검문제
p.269
1. 주로 상속 계층에서 추상적인 개념을 나타내기 위한 용도로 사용
2. 추상 클래스는 일반 메소드도 포함한다
3. 반드시 추상 메소드를 구현해야 한다.
p.277
1. 객체와 객체 사이의 상호 작용을 위하여 사용
2. 하나의 클래스는 여러 개의 인터페이스를 동시에 구현할 수 있다.
3. 선언할 수 없다.
p.279
1. 인터페이스도 클래스와 마찬가지로 타입이라고 생각할 수 있다. 따라서 참조 변수를 정
의하는데 사용될 수 있다
2. 여러 클래스에서 사용되는 상수를 정의하면 그 인터페이스를 구현하는 클래스들은 자동
적으로 인터페이스에 정의된 상수들을 공유하게 된다.
3. 인터페이스를 사용하여 다중 상속의 효과를 낸다.
p.287
1. 수퍼 클래스 참조 변수가 서브 클래스 객체를 참조하는 것은 가능하지만, 서브 클래스의
참조 변수가 수퍼 클래스의 객체를 참조하는 것은 문법적인 오류이다.
2. A instanceof B 일때, 객체 A가 클래스 B로 생성되었으면 true를 반환
3. 동일한 수퍼 클래스에서 상속된 서브 클래스의 객체들을 하나의 타입으로 취급할 때 유
용하다
4. 수퍼 클래스 타입으로 선언하는 것이 좋다
p.289
1. 내부클래스는 하나의 클래스 안에 다른 클래스를 정의하는 것으로 클래스의 모든 멤버를
참조할 수 있다.
2. 내부 클래스는 private로 선언된 필드도 접근이 가능하다.
p.291
1. new 키워드 다음에 수퍼 클래스 이름이나 인터페이스 이름을 적어준다
2. 무명 클래스를 정의하면 클래스 정의와 객체 생성을 동시에 할 수 있다.
3. new Object() { ... }
Lab
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class CallbackTest {
public static void main(String[] args) {
ActionListener listener = new MyClass();
Timer t = new Timer(1000, listener);
t.start();
for (int i = 0; i < 1000; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}
class MyClass implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("beep");
}
}
Exercise
1.
class AudioSystem extends SoundSystem implements MP3playable, TurnTableplayable
{
...
}
2. 인터페이스 안에는 추상 메소드만 정의할 수 있다.
public interface MyInterface {
void MyMethod(int value);
}
3.
abstract class Bird
{
abstract public void sound();
}
class Dove extends Bird
{
public void sound()
{
System.out.println("coo coo");
}
}
4.
public interface Edible {
//boolean amount; 필드는 정의할 수 없다.
final int TYPE=10;
public void eat(); // {
};
추상 메소드만 정의할 수 있다.
};
public class Sandwitch implements Edible {
public void eat() {
}
}
5. (2)
6. (3)
7. a, b, c, d
9.
(1) 수퍼 클래스 참조 변수는 서브 클래스 객체를 가리킬 수 있다.
(2) 가능하다.
(3) 오타! 다음과 같은 문장은 적법한가? 그 이유는?
Point3D p = new Point2D();
-> 적법하지 않다. 수퍼 클래스 객체를 서브 클래스 참조 변수로 가리킬 수 없다.
(4)
class Point2D{
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
private int x;
private int y;
}
class Point3D extends Point2D{
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
private int z;
}
Programming
1.
interface Movable
{
void move(int dx, int dy);
}
class Shape implements Movable {
protected int x, y;
public void draw() {
System.out.println("Shape Draw");
}
public void move(int dx, int dy) {
x = dx;
y = dy;
}
};
class Rectangle extends Shape {
private int width, height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public void draw() {
System.out.println("Rectangle Draw");
}
};
class Triangle extends Shape {
private int base, height;
public void draw() {
System.out.println("Triangle Draw");
}
@Override
public void move(int dx, int dy) {
x = dx;
y = dy;
}
};
class Circle extends Shape {
private int radius;
public void draw() {
System.out.println("Circle Draw");
}
};
public class ShapeTest {
private static Movable arrayOfShapes[];
public static void main(String arg[]) {
init();
moveAll();
}
public static void init() {
arrayOfShapes = new Shape[3];
arrayOfShapes[0] = new Rectangle();
arrayOfShapes[1] = new Triangle();
arrayOfShapes[2] = new Circle();
}
public static void moveAll() {
for (int i = 0; i < arrayOfShapes.length; i++) {
arrayOfShapes[i].move(10, 10);
}
}
};
2. 오타! 다음과 같이 수정하여 주세요.
다음과 같은 인터페이스들을 정의하라.
public interface Drawable
{
void draw();
}
본문의 ShapeTest.java에 등장하는 2차원 도형인 원, 사각형, 삼각형 등이 위의 인터페이스
를 구현하도록 수정하라. draw() 메소드에서는 실제로 그리지는 않고 메시지만을 출력하라.
main()에서 Drawable 객체 배열을 생성하고 배열의 각 원소에 대하여 draw()를 호출하는
프로그램을 작성하라.
interface Drawable {
void draw();
}
class Shape implements Drawable {
protected int x, y;
public void draw() {
System.out.println("Shape Draw");
}
};
class Rectangle extends Shape {
private int width, height;
public void setWidth(int w) {
width = w;
}
public void setHeight(int h) {
height = h;
}
public void draw() {
System.out.println("Rectangle Draw");
}
};
class Triangle extends Shape {
private int base, height;
public void draw() {
System.out.println("Triangle Draw");
}
};
class Circle extends Shape {
private int radius;
public void draw() {
System.out.println("Circle Draw");
}
};
public class ShapeTest {
private static Drawable arrayOfShapes[];
public static void main(String arg[]) {
init();
drawAll();
}
public static void init() {
arrayOfShapes = new Shape[3];
arrayOfShapes[0] = new Rectangle();
arrayOfShapes[1] = new Triangle();
arrayOfShapes[2] = new Circle();
}
public static void drawAll() {
for (int i = 0; i < arrayOfShapes.length; i++) {
arrayOfShapes[i].draw();
}
}
};
3.
interface controllable {
void play();
void stop();
}
public class Test {
public static void main(String arg[]) {
controllable c = new controllable() {
public void play() {
System.out.println("PLAY");
}
public void stop() {
System.out.println("STOP");
}
};
c.play();
c.stop();
}
};
4.
interface Comparable {
// 이 객체가 다른 객체보다 크면 1, 같으면 0, 작으면 -1을 반환한다.
int compareTo(Object other);
}
class Person implements Comparable {
@Override
public String toString() {
return "Person [name=" + name + ", height=" + height + "]";
}
public Person(String name, double height) {
super();
this.name = name;
this.height = height;
}
String name;
double height;
@Override
public int compareTo(Object other) {
if ( this.height > ((Person)other).height )
return 1;
else if ( this.height == ((Person)other).height )
return 0;
else
return -1;
}
}
public class Test {
public static Person getMaximum(Person[] array)
{
Person max=array[0];
for(int i=1;i<array.length;i++){
if( array[i].height > max.height )
max = array[i];
}
return max;
}
public static void main(String arg[]) {
Person[] array;
array = new Person[3];
array[0] = new Person("홍길동1", 190);
array[1] = new Person("홍길동2", 180);
array[2] = new Person("홍길동3", 185);
System.out.println(getMaximum(array));
}
}
5. 생략
6. 생략
CHAPTER 13
중간점검문제
p.306
1. 컴포넌트
2. AWT는 운영체제에서 제공하는 컴포넌트를 그대로 사용한 것이다. 스윙은 자바가 직접 각
컴포넌트를 작성한 것이다.
3. 스윙에서 기본적으로 제공된다.
4. setVisible() 메소드는 Window 클래스에서 제공한다. 따라서 Window를 상속받는 클래스들
이 사용할 수 있다. 예를 들어서 JFrame 클래스가 사용할 수 있다.
p.308
1. 다른 컴포넌트들을 내부에 넣을 수 있는 기능을 가진다.
2. 절대 다른 컨테이너 안에 포함 될 수 없는 컨테이너로 프레임, 다이알로그, 애플릿이 있
다.
p.313
1. 프레임 객체 생성 -> 버튼 생성 -> 버튼을 프레임에 추가
2.
class MyFrame extends JFrame {
public MyFrame() {
...
JButton button1 = new JButton("버튼1");
JButton button2 = new JButton("버튼2");
this.add(button1);
this.add(button2);
}
}
p.323
1.
class MyFrame extends JFrame {
public MyFrame() {
...
JLabel label = new JLabel("레이블");
JButton button = new JButton("버튼");
this.add(label);
this.add(button);
}
}
2. 패널에 버튼을 추가하면 버튼3개가 나란히 보이지만, 프레임에 버튼 3개를 추가하면 마지
막 버튼만 프레임 전체에 보인다.
Exercise
1.
(1) JButton
(2) 버튼, 레이블, 텍스트 필드 등
(3) JFrame클래스를 확장하여야 한다.
(4) 화면에 표시되어서 사용자와 상호 작용하는
getWidth(), getX(), setFont()등이 사용된다.
시각적인
객체를
나타내며
add(),
(5) 컨테이너 생성 -> 컴포넌트 생성 -> 컴포넌트를 컨테이너에 추가
2.
(1)
(2)
(3)
(4)
거짓
거짓
거짓
거짓
3.
(1)
(2)
(3)
(4)
import javax.swing.*;
button = new JButton("동작");
JButton button1, button2;
JLabel label = new JLabel();
-
패널은 다른 패널을 포함할 수 있다.
스윙의 컴포넌트 수가 AWT 보다 많다.
add()
프레임은 최상위 컨테이너라 다른 컨테이너 안에 포함될 수 없다.
4.
(1) JLabel, JButton, JPanel, JFrame
(2) setSize(500,100);
(3) JPanel panel = new JPanel();
(4) JLabel label = new JLabel("자바는 재미있나요?");
(5)
JButton button1 = new JButton("Yes");
JButton button2 = new JButton("No");
(6)
panel.add(label);
panel.add(button1);
panel.add(button2);
(7) add(panel);
Programming
1.
import java.awt.*;
import javax.swing.*;
class TestFrame extends JFrame{
public TestFrame(){
setSize(500,100);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("테스트 프레임");
JPanel panel = new JPanel();
JLabel label = new JLabel("자바는 재미있나요?");
JButton button1 = new JButton("Yes");
JButton button2 = new JButton("No");
panel.add(label);
panel.add(button1);
panel.add(button2);
add(panel);
setVisible(true);
}
}
public class TestFrameT{
public static void main(String[] args){
TestFrame f = new TestFrame();
}
}
2.
import java.awt.*;
import javax.swing.*;
class MyFrame extends JFrame{
public MyFrame(){
setSize(500,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("테스트 프레임");
JPanel panel1 = new JPanel();
JLabel label1 = new JLabel("인간에게 주어진 최사의 선물은 마음껏 웃을
수 있다는 것이다.");
JLabel label2 = new JLabel("가능한 목표라고 하더라도 그것을 꿈꾸고 상
상하는 순간 이미 거기에 다가가 있는 것이다. ");
JLabel label3 = new JLabel("상상력은 생존의 힘이다.");
panel1.add(label1);
panel1.add(label2);
panel1.add(label3);
add(panel1);
setVisible(true);
}
}
public class MyFrameTest{
public static void main(String[] args){
MyFrame f = new MyFrame();
}
}
3.
import java.awt.*;
import javax.swing.*;
class MyFrame extends JFrame{
public MyFrame(){
setSize(400,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("테스트 프레임");
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JLabel label1 = new JLabel("자바 호텔에 오신 것을 환영합니다.");
JLabel label2 = new JLabel("숙박일수를 입력하세요.");
JButton button1 = new JButton("1명");
JButton button2 = new JButton("2명");
JButton button3 = new JButton("3명");
JButton button4 = new JButton("4명");
JButton button5 = new JButton("5명");
panel1.add(label1);
panel1.add(label2);
panel2.add(button1);
panel2.add(button2);
panel2.add(button3);
panel2.add(button4);
panel2.add(button5);
panel3.add(panel1);
panel3.add(panel2);
add(panel3);
setVisible(true);
}
}
public class MyFrameTest{
public static void main(String[] args){
MyFrame f = new MyFrame();
}
}
CHAPTER 14
Lab
import
import
import
import
java.awt.FlowLayout;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JPanel;
class MyFrame extends JFrame {
JPanel p1;
public MyFrame() {
setSize(300, 200);
setTitle("My Frame");
p1 = new JPanel();
p1.setLayout(new FlowLayout());
for (int i = 0; i < 10; i++)
p1.add(new JButton("Button" + i));
add(p1);
setVisible(true); // 프레임을 화면에 표시한다.
}
}
public class MyFrameTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}
Exercise
1. 마지막에 추가한 버튼이 다른 버튼들을 전부 가리게 된다.
2.
컨테이너
프레임(frame)
패널(pannel)
애플릿(applet)
디폴트 배치 관리자
BorderLayout
FlowLayout
FlowLayout
3. GridLayout(1, 0)
4.
import
import
import
import
java.awt.Color;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
class MyFrame extends JFrame {
JPanel p = new JPanel();
JLabel[] labels = new JLabel[30];
public MyFrame() {
p.setLayout(null);
for (int i = 0; i < 30; i++) {
labels[i] = new JLabel("" + i);
int x = (int) (500 * Math.random());
int y = (int) (200 * Math.random());
labels[i].setForeground(Color.MAGENTA);
labels[i].setLocation(x, y);
labels[i].setSize(20, 20);
p.add(labels[i]);
}
setSize(500, 300);
add(p);
setVisible(true); // 프레임을 화면에 표시한다.
}
}
public class MyFrameTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}
Programming
1.
// 패키지 포함
import java.awt.GridLayout;
import
import
import
import
import
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JTextField;
// JFrame을 상속받는 MyFrame 클래스 선언
class MyFrame extends JFrame {
// 필드선언
private JButton button;
private JLabel label;
private JTextField textInput,textResult;
private JPanel panel,panel1,panel2,panel3;
// 생성자 선언
public MyFrame()
{
setSize(500,200); // 프레임의 크기 설정
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 종료버튼을 눌렀을때 프레임이 닫히도록 설정
setTitle("마일을 킬로미터로 변환"); // 프레임의 제목 설정
panel = new JPanel(); // panel에 패널 객체 생성
panel.setLayout(new GridLayout(0, 1));
panel1 = new JPanel(); // panel에 패널 객체 생성
panel2 = new JPanel(); // panel에 패널 객체 생성
panel3 = new JPanel(); // panel에 패널 객체 생성
label= new JLabel("거리를 마일 단위로 입력하세요"); // label에 레이블
객체 생성
textInput = new JTextField(10); // textInput에 텍스트 필드 객체 생성
panel1.add(label); // 패널에 레이블 추가
panel1.add(textInput); // 패널에 텍스트 필드 추가
button = new JButton("변환"); // button에 버튼 객체 생성
panel2.add(button); // 패널에 버튼 추가
textResult = new JTextField(30); // textResult에 크기가 30인 텍스트 필
드 객체 생성
panel3.add(textResult); // 패널에 텍스트 필드 추가
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
add(panel); // 프레임에 패널 추가
setVisible(true); // 프레임 출력 메소드
}
}
public class MyFrameTest {
public static void main(String[] args) {
MyFrame f = new MyFrame(); // 객체 생성
}
}
2.
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.*;
class Myframe extends JFrame
{
JButton button;
JTextField t1;
JTextField t2;
JTextField t3;
private JPanel panel,panel1,panel2,panel3, panel4;
public Myframe()
{
setSize(230,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("이자 계산기");
JPanel
JPanel
JPanel
JPanel
JPanel
panel=new JPanel(new GridLayout(0, 1));
panel1=new JPanel();
panel2=new JPanel();
panel3=new JPanel();
panel4=new JPanel();
JLabel label1=new JLabel("원금을 입력하시오");
t1=new JTextField(5);
panel1.add(label1);
panel1.add(t1);
JLabel label2=new JLabel("이율을 입력하시오");
t2=new JTextField(5);
panel2.add(label2);
panel2.add(t2);
button=new JButton("변환");
panel3.add(button);
t3=new JTextField(20);
panel4.add(t3);
panel.add(panel1);
panel.add(panel2);
panel.add(panel3);
panel.add(panel4);
this.add(panel);
setVisible(true);
}
}
public class MyFrameTest {
public static void main(String[] arge)
{
Myframe f=new Myframe();
}
}
3. 오타! 문제의 그림을 다음과 같이 수정하여 주세요.
윈도우 제목
계산기
텍스트 필드
23
C
7
8
9
/
4
5
6
*
1
2
3
-
0
+/-
=
+
버튼
import java.awt.FlowLayout;
import java.awt.GridLayout;
import
import
import
import
import
javax.swing.BoxLayout;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.JTextField;
class MyFrame extends JFrame {
public MyFrame() {
JPanel p, p1, p2, p3;
JTextField tf;
JButton[] b = new JButton[17];
p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.Y_AXIS));
p1 = new JPanel();
FlowLayout layout = new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);
layout.setVgap(0);
p1.setLayout(layout);
p2 = new JPanel();
p2.setLayout(layout);
p3 = new JPanel(new GridLayout(0, 4));
tf = new JTextField(30);
p1.add(tf);
b[0] = new JButton("C");
b[1] = new JButton("7");
b[2] = new JButton("8");
b[3] = new JButton("9");
b[4] = new JButton("/");
b[5] = new JButton("4");
b[6] = new JButton("5");
b[7] = new JButton("6");
b[8] = new JButton("*");
b[9] = new JButton("1");
b[10] = new JButton("2");
b[11] = new JButton("3");
b[12] = new JButton("-");
b[13] = new JButton("0");
b[14] = new JButton("+/-");
b[15] = new JButton("=");
b[16] = new JButton("+");
p2.add(b[0]);
for (int i=1; i<17; i++) {
p3.add(b[i]);
}
p.add(p1);
p.add(p2);
p.add(p3);
add(p);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
}
public class MyFrameTest {
public static void main(String[] args) {
new MyFrame();
}
}
CHAPTER 15
중간점검문제
p.360
1. 오류: 아직 이벤트 처리를 학습하지 않았는데 문제가 이벤트 처리를 요구하고 있습니다.
다음과 같이 문제를 변경하여 주십시오.
SnowManFace에서 찡그린 얼굴을 그리도록 소스를 수정하라.
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Color;
java.awt.Graphics;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyPanel extends JPanel {
int type = 0;
public void paintComponent(Graphics g) {
super.paintComponent(g);
if( type == 0 ){
g.setColor(Color.YELLOW);
g.fillOval(20, 30, 200, 200);
g.setColor(Color.BLACK);
g.drawArc(60, 80, 50, 50, 180, -180); // 왼쪽 눈
g.drawArc(150, 80, 50, 50, 180, -180); // 오른쪽 눈
g.drawArc(70, 130, 100, 70, 180, 180); // 입
}
else {
g.setColor(Color.YELLOW);
g.fillOval(20, 30, 200, 200);
g.setColor(Color.BLACK);
g.drawArc(60, 80, 50, 50, 180, +180); // 왼쪽 눈
g.drawArc(150, 80, 50, 50, 180, +180); // 오른쪽 눈
g.drawArc(70, 130, 100, 70, 180, 180); // 입
}
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
repaint();
}
}
public class SnowManFace extends JFrame implements ActionListener{
MyPanel panel;
public SnowManFace() {
setSize(280, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("눈사람 얼굴");
setVisible(true);
panel = new MyPanel();
add(panel);
JButton b = new JButton("찡그린 얼굴");
add(b, BorderLayout.SOUTH);
b.addActionListener(this);
}
public static void main(String[] args) {
SnowManFace s = new SnowManFace();
}
@Override
public void actionPerformed(ActionEvent arg0) {
panel.setType(1);
}
}
2. 생략
p.368
1. myLabel.setFont(new Font("Dialog", Font.ITALIC, 10));
Lab
1.
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyComponent extends JComponent
// JComponent 를 상속받은 MyComponent 클래스 생성
{
public void paint(Graphics g) // paint 메소드 재정의
{
g.drawLine(10, 80, 100, 10);
// x, y좌표 10, 80부터 100, 10까지 선긋기
g.drawString("drawLine()", 10, 100);
// x, y좌표 10, 100에 문자열 그리기
g.drawRect(110, 10, 110, 80);
// x, y좌표 10, 80부터 100, 10까지 사각형 그리기
g.drawString("drawRect()", 110, 100);
// x, y좌표 10, 100에 문자열 그리기
//
}
①
}
public class Test
{
public static void main(String[] args)
{
JFrame frame = new JFrame(); // JFrame 객체 생성
frame.setSize(800, 300);
// 프레임 사이즈
frame.setTitle("그리기");
// 프레임 제목
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyComponent component = new MyComponent();
// MyComponent객체 생성
frame.add(component);
frame.setVisible(true);
// Component를 프레임에 추가
// 프레임을 보이게 함
}
}
① 위의 소스를 분석하고 주석을 달아라.
② ①번 위치에 나머지 도형들을 그리는 문장들을 추가하라.
- 도형들을 그리는 draw메소드를 호출해서 도형을 생성하고 그 밑에 drawString메소드를 사
용해 어떤 도형인지를 문자열로 나타내준다. 각 도형마다 Graphics객체를 통하여 메소드를
호출한다. 각 도형마다 매개변수로 보내줘야 할 변수들이 다르기 때문에 각 메소드를 충분
히 숙지하고 사용해야 한다.
도형을 그리는 색상을 변경하여 보자. 예를 들어서 사각형의 색상을 빨간색으로 변경하
여 보라.
- g.setColor(Color.RED);
이처럼 역시 객체 g를 통해 색에 관한 설정자를 불러 색을 바꿔준다.
텍스트 "drawRect()" 의 폰트를 "Serif", 12포인트, 볼드체로 변경하여 보자.
- g.setFont(new Font("Serif", Font.BOLD, 12));
이처럼 Font설정자를 불러 텍스트를 형태를 바꿔준다.
drawArc()의 각도를 변경하여 보자.
- 설정자를 통해 각도를 설정하는 방법도 있지만 밑 소스에서는 도형을 초기화 할 때 각도
를 다르게 해주었다.
③
④
⑤
import java.awt.*;
import javax.swing.*;
class MyComponentextends JComponent
{
public void paint(Graphics g)
{
setForeground(Color.gray);
//3D 효과를 돋보이게 하기 위해 색을 gray로 바꾸어줌
setBackground(Color.gray);
//도형을 그리고 문자열 출력을 반복
g.setColor(Color.RED);
//색깔을 바꿔주는 설정자 호출, 빨간색으로 선색을 바꿈
g.drawLine(10, 80, 100, 10);
//선
g.drawString("drawLine()", 10, 100); //문자열 출력
g.drawRect(110, 10, 110, 80); //사각형
g.setFont(new Font("Serif", Font.BOLD, 12));
//글자체 변경
g.drawString("drawRect()", 110, 100);
g.setFont(new Font("sansSerif", Font.PLAIN, 12)); //글자체 변경
g.draw3DRect(230, 10, 110, 80, true);
//3D 사각형
g.drawString("draw3DRect()", 230, 100);
g.setColor(Color.BLUE);
//파란색으로 색을 채워줌
g.drawRoundRect(350, 10, 110, 80, 20, 20);
//둥근 모서리 사각형
g.drawString("drawRoundRect()", 350, 100);
g.drawOval(470, 10, 110, 80); //타원
g.drawString("drawOval()", 470, 100);
g.drawArc(590, 10, 110, 80, 80, 230); //아크 도형
g.drawString("drawArc()", 590, 100);
g.setColor(Color.GREEN);
//초록색으로 색을 바꿔줌
int[] xPoints = {720, 830, 720, 830};
//x 좌표 배열 생성
int[] yPoints = {10, 10, 90, 90};
//y 좌표 배열 생성
int nPoints = 4;
//점의 개수
g.drawPolygon(xPoints, yPoints, nPoints);
//x, y 좌표를 이용해 nPoints 만큼 점을 만든 다음 선을 이어줌
g.drawString("drawPolygon()", 720, 100);
g.fillRect(110, 120, 110, 80);
//색이 채워진 사각형
g.drawString("drawRect()", 110, 210);
g.setColor(Color.orange);
//오렌지 색으로 바꿈
g.fill3DRect(230, 120, 110, 80, true);
//색이 채워진 3D 사각형
g.drawString("draw3DRect()", 230, 210);
g.fillRoundRect(350, 120, 110, 80, 20, 20);
//색이 채워진 둥근 모서리 사각형
g.drawString("drawRoundRect()", 350, 210);
g.setColor(Color.PINK);
g.fillOval(470, 120, 110, 80);
//색이 채워진 타원
g.drawString("drawOval()", 470, 210);
g.fillArc(590, 120, 110, 80, 90, 120);
//색이 채워진 아크 도형
g.drawString("drawArc()", 590, 210);
int[] x = {720, 830, 720, 830};
int[] y = {120, 120, 200, 200};
int n = 4;
g.fillPolygon(x, y, n);
//색이 채워진 폴리건
g.drawString("fillPolygon()", 720, 210);
}
}
public class Test {
public static void main(String[] args)
{
JFrame frame = new JFrame();
// JFrame 객체 생성
frame.setSize(900, 300);
// 프레임 사이즈
frame.setTitle("그리기");
// 프레임 제목
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyComponent component = new MyComponent();
// MyComponent객체 생성
frame.add(component);
frame.setVisible(true);
}
}
// Component를 프레임에 추가
// 프레임을 보이게 함
2. 생략(책의 본문에 있는 프로그램과 유사)
3.
import java.awt.*;
import javax.swing.*;
class MyComponent extends JComponent
//JComponent를 상속받은 MyComponent
{
public void paint(Graphics g)
//paint메소드 재정의
{
int x=10;
//x좌표 초기화
int w1=110; //타원의 가로, 즉 지름
for(int i=2 ; i<7 ; i++)
{
g.drawOval(x, 10, w1, 80); //타원을 그려줌
g.drawString("r = "+w1/2, x+w1/2, 50);
//타원안에 반지름 길이 표시
x+=w1+20;
w1+=i;
//타원하나를 그릴 때마다 다음 타원은 지금의 타원과
20 만큼 거리를 둠
//가로의 길이를 늘려줌
}
//정렬된 모습을 보여주기 위해 5개의 타원은 위에 그리고 나머지 타원은 아래에 그려줌
x=10;
//x좌표를 다시 초기화
for(int i=2 ; i<7 ; i++)
{
g.drawOval(x, 120, w1, 80);
//타원을 그려줌
g.drawString("r = "+w1/2, x+w1/2, 160);
//타원안에 반지름 길이 표시
x+=w1+20;
w1-=i;
//타원하나를 그릴 때마다 다음 타원은 지금의 타원과
20 만큼 거리를 둠
//가로의 길이를 줄여줌
}
}
}
public class Test {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(750, 250);
frame.setTitle("그리기");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyComponent component = new MyComponent();
frame.add(component);
frame.setVisible(true);
}
}
4. (생략)
Exercise
1. 다음 질문에 간단히 답하라.
(1) java.awt
(2) Color
(3) Font
(4) (0, 0)
(5) 픽셀
(6) Graphics
2. 아래 문장의 참, 거짓을 판단하고 거짓이면 그 이유를 말하라.
(1) 거짓 - 위에서 아래쪽으로 증가한다.
(2) 참
(3) 참
(4) 거짓 - 0부터 255까지
(5) 거짓 - 감싸는 사각형의 좌측 상단의 좌표이다.
3. 다음에서 잘못된 것을 고쳐라. 다음 코드에서 g는 Graphics 객체를 나타낸다.
(1) g.setFont(new Font("Serif", Font.PLAIN, 10));
(2) g.setColor(Color.White);
(3) Font f = new Font("Serif", Font.BOLD| Font.ITALIC, 12);
(4) Graphics 객체는 사용자가 생성할 수 없다.
(5) g.setColor(new Color(255, 0, 255));
4. 자바에서 색상은 어떻게 표현되는가?
빛의 3원색인 Red 성분, Green 성분, Blue 성분이 얼마나 함유되어 있는지를 0에서 255까
지의 수를 사용하여 나타낸다. 예를 들어 흰색은 (255, 255, 255)가 되고 검정색은 (0, 0,
0), 노란색은 (255, 255, 0)으로 표현된다.
5. 자바에서 다각형을 표현하는 2가지 방법은 무엇인가?
자바에서 다각형은 Polygon 객체를 이용하여서 다각형을 표현할 수 있다.
(1) 다각형을 배열을 이용하여 표현하고 Polygon 생성자를 호출한다. Polygon(int[] xpoints,
int[] ypoints, int npoints)와 같은 생성자를 사용한다.
(2) Polygon()을 호출하여서 비어 있는 Polygon 객체를 먼저 생성하고 나중에 다각형의 정점
들을 추가하여도 된다.
Polygon p = new Polygon();
p.addPoint(10, 10);
Programming
1.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MyPanel extends JPanel {
Font f1, f2, f3, f4, f5;
public MyPanel() {
f1 = new Font("Serif", Font.PLAIN, 20);
f2 = new Font("San Serif", Font.BOLD, 20);
f3 = new Font("Monospaced", Font.ITALIC, 20);
f4 = new Font("Dialog", Font.BOLD | Font.ITALIC, 20);
f5 = new Font("DialogInput", Font.BOLD, 20);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=0; i< 10; i++) {
g.setFont(f1);
Color color = new Color((int) (Math.random() * 255.0),
(int)
(Math.random()
*
255.0),
(Math.random() * 255.0));
g.setColor(color);
g.drawString("Hello World!", 10, 50+i*20);
}
}
}
public class FontTest extends JFrame {
public FontTest() {
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Font Test");
JPanel panel = new MyPanel();
add(panel);
setVisible(true);
}
public static void main(String[] args) {
FontTest s = new FontTest();
}
}
2.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MyPanel extends JPanel {
Font[] fonts = new Font[5];
public MyPanel() {
fonts[0] = new Font("Serif", Font.PLAIN, 20);
fonts[1] = new Font("San Serif", Font.BOLD, 20);
fonts[2] = new Font("Monospaced", Font.ITALIC, 20);
fonts[3] = new Font("Dialog", Font.BOLD | Font.ITALIC, 20);
fonts[4] = new Font("DialogInput", Font.BOLD, 20);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for(int i=0; i< 10; i++) {
(int)
g.setFont(fonts[(int)(Math.random()*5.0-0.01)]);
g.drawString("Hello World!", 10, 50+i*20);
}
}
}
public class FontTest extends JFrame {
public FontTest() {
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Font Test");
JPanel panel = new MyPanel();
add(panel);
setVisible(true);
}
public static void main(String[] args) {
FontTest s = new FontTest();
}
}
3. 생략(Lab 문제와 유사)
4.
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
class House extends JPanel {
public House()
{
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2=(Graphics2D) g;
g2.setStroke(new BasicStroke(3));
g2.setColor(Color.BLACK);
g2.draw(new Rectangle2D.Float(50,50,200,200));
g2.draw(new Rectangle2D.Float(150,150,50,100));
g2.draw(new Rectangle2D.Float(75,75,20,20));
g2.draw(new Line2D.Float(150, 20, 50, 50));
g2.draw(new Line2D.Float(150, 20, 250, 50));
}
}
class MyFrame extends JFrame{
public MyFrame()
{
setSize(300,300);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
House H=new House();
H.setBounds(0, 0, 300, 300);
add(H);
setVisible(true);
}
}
public class Test {
public static void main(String[] arge)
{
MyFrame F=new MyFrame();
}
}
5.
import java.awt.*;
import javax.swing.*;
class BusinessCard extends JPanel {
public BusinessCard()
{
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("홍길동", 150, 40);
g.drawString("프로젝트 매니저", 150, 60);
g.drawString("자바주식회사", 150, 80);
g.setColor(Color.red);
g.fillOval(20, 20, 80, 80);
}
}
class MyFrame extends JFrame{
public MyFrame()
{
setSize(300,150);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new BusinessCard());
setVisible(true);
}
}
public class Test {
public static void main(String[] arge)
{
MyFrame F=new MyFrame();
}
}
6.
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.awt.geom.*;
class MyPanel extends JPanel
{
public MyPanel()
{
super();
setBackground( Color.yellow );
setSize( 400, 400 );
}
public void paintComponent( Graphics g )
{
super.paintComponent(g);
int xPoints[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int yPoints[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath star = new GeneralPath();
star.moveTo( xPoints[ 0 ], yPoints[ 0 ] );
for ( int k = 1; k < xPoints.length; k++ )
star.lineTo( xPoints[ k ], yPoints[ k ] );
star.closePath();
g2d.translate( 100, 100 );
for ( int j = 1; j <= 5; j++ )
{
g2d.rotate( Math.PI / 30.0 );
g2d.setColor(new Color( ( int ) ( Math.random() * 256 ),( int )
( Math.random() * 256 ),
( int ) ( Math.random() * 256 ) ) );
g2d.fill( star ); // draw a filled star
}
}
}
public class MyFrame extends JFrame{
public MyFrame()
{
setSize(300,300);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new MyPanel());
setVisible(true);
}
public static void main(String[] arge)
{
MyFrame F=new MyFrame();
}
}
7.
/* SkyscraperApplet.java */
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
class Skyscraper {
public int
public int
public int
public int
x;
y;
width;
height;
Skyscraper(int x, int y, int w, int h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
}
void draw(Graphics g) {
Color color = new Color((int) (Math.random() * 255.0),
(int) (Math.random() * 255.0), (int) (Math.random() *
255.0));
g.setColor(color);
g.fillRect(x, y, width, height);
}
}
class MyPanel extends JPanel {
Skyscraper[] s = new Skyscraper[10];
public MyPanel() {
super();
for (int i = 0; i < 10; i++) {
s[i] = new Skyscraper((int) (Math.random() * 500),
(int)
(Math.random()
*
300),
(Math.random() * 500),
(int) (Math.random() * 300));
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int i = 0; i < 10; i++) {
s[i].draw(g);
}
}
}
public class MyFrame extends JFrame {
public MyFrame() {
setSize(500, 300);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new MyPanel());
setVisible(true);
}
public static void main(String[] arge) {
MyFrame F = new MyFrame();
}
}
(int)
8. 생략(앞의 문제와 유사함)
9. 이벤트 처리는 아직 학습하지 않았지만 문제를 흥미롭게 하기 위하여 추가하였다.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
class DoubleDice extends JPanel implements MouseListener {
int die1 = 4;
int die2 = 3;
public DoubleDice() {
super();
addMouseListener(this);
setBackground(new Color(200, 200, 255));
}
public void paintComponent(Graphics g) {
drawDie(g, die1, 10, 10);
drawDie(g, die2, 55, 55);
}
void drawDie(Graphics g, int val, int x, int y) {
g.setColor(Color.white);
g.fillRect(x, y, 35, 35);
g.setColor(Color.black);
g.drawRect(x, y, 34, 34);
if (val > 1)
g.fillOval(x + 3, y + 3, 9, 9);
if (val > 3)
g.fillOval(x + 23, y + 3, 9, 9);
if (val == 6)
g.fillOval(x + 3, y + 13, 9, 9);
if (val % 2 == 1)
g.fillOval(x + 13, y + 13, 9, 9);
if (val == 6)
g.fillOval(x + 23, y + 13, 9, 9);
if (val > 3)
g.fillOval(x + 3, y + 23, 9, 9);
if (val > 1)
g.fillOval(x + 23, y + 23, 9, 9);
}
void roll() {
die1 = (int) (Math.random() * 6) + 1;
die2 = (int) (Math.random() * 6) + 1;
repaint();
}
public void mousePressed(MouseEvent evt) {
roll();
}
public void mouseReleased(MouseEvent evt) {
}
public void mouseClicked(MouseEvent evt) {
}
public void mouseEntered(MouseEvent evt) {
}
public void mouseExited(MouseEvent evt) {
}
}
public class MyFrame extends JFrame {
public MyFrame() {
setSize(100, 180);
setTitle("MyFrame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(new DoubleDice());
setVisible(true);
}
public static void main(String[] arge) {
MyFrame F = new MyFrame();
}
}
10.
// awt와 swing 패키지 포함
import java.awt.*;
import javax.swing.*;
// JComponent를 상속 받는 Mycomponent 클래스 선언
class Car extends JComponent {
// 자동차의 색상과 위치(좌표), 크기를 받을 필드 선언
private String color;
private int size1;
private int size2;
private int location1;
private int location2;
// 각 필드를 매개변수로 받는 생성자 선언
public Car(String color, int location1, int location2, int size1, int size2){
this.color = color;
this.size1 = size1;
this.size2 = size2;
this.location1 = location1;
this.location2 = location2;
}
// paint() 메소드를 재정의하여 자동차의 그림을 그림
public void paint(Graphics g){
// 자동차 차체의 색상 설정
g.setColor(Color.green);
// fillRect()메소드를 사용하여 사용자로부터 입력받은 좌표와 크기로 몸
체(사각형)를 그림
g.fillRect(location1, location2, size1, size2);
// 창문의 색상 설정
g.setColor(Color.white);
/* fillRect()메소드를 사용하여 사용자로부터 입력받은 좌표를 수정해 몸체
안에 폭 30,
너비 30의 창문(사각형)을 2개 만듬*/
g.fillRect(location1+10, location2+10, 30, 30);
g.fillRect(location1+50, location2+10, 30, 30);
// 자동차 바퀴의 색상 설정
g.setColor(Color.black);
/* fillOval()메소드를 사용하여 사용자로부터 입력받은 좌표를 수정해 폭
25, 너비 25의
바퀴(원)을 2개 만듬*/
g.fillOval(location1, location2+size2, 25, 25);
g.fillOval(location1+size1-25, location2+size2, 25, 25);
}
}
public class Test {
// Test 클래
스 선언
public static void main(String args[]){ // 메인 메소드 선언
// Jframe 타입의 참조변수 frame을 선언해 객체를 가르키도록 함
JFrame frame = new JFrame();
frame.setSize(1200, 500); // 프레임의 사이즈 설정
frame.setTitle("그리기");
// 타이틀을 "그리기"로 설정
// 컴포넌트를 격자모양으로 배치하는 배치관리자 GridLayout 설정
frame.setLayout(new GridLayout());
// x버튼을 누를시 프로그램이 종료되도록 설정
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Car car1 = new Car("blue", 10, 10, 200, 100);
// 첫 번째 car 객체
Car car2 = new Car("red", 10, 300, 150, 80);
// 두 번째 car 객체
Car car3 = new Car("green", 5, 150, 250, 150);
// 세 번째 car 객체
Car car4 = new Car("black", 100, 200, 100, 70);
// 네 번째 car 객체
생성
생성
생성
생성
// car객체들을 프레임에 포함
frame.add(car1);
frame.add(car2);
frame.add(car3);
frame.add(car4);
// 프레임을 화면에 보이도록 시각화 함
frame.setVisible(true);
}
}
11. 이벤트 처리는 아직 학습하지 않았지만 문제를 흥미롭게 하기 위하여 추가하였다.
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Color;
java.awt.Graphics;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
class MyPanel extends JPanel implements ActionListener {
boolean flag = false;
private int light_number = 0;
public MyPanel() {
setLayout(new BorderLayout());
JButton b = new JButton("신호변경");
b.addActionListener(this);
add(b, BorderLayout.SOUTH);
}
@Override
protected void paintComponent(Graphics g) {
// TODO Auto-generated method stub
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawOval(100, 100, 100, 100);
g.drawOval(100, 200, 100, 100);
g.drawOval(100, 300, 100, 100);
if (light_number == 0) {
g.setColor(Color.RED);
g.fillOval(100, 100, 100, 100);
} else if (light_number == 1) {
g.setColor(Color.GREEN);
g.fillOval(100, 200, 100, 100);
} else {
g.setColor(Color.YELLOW);
g.fillOval(100, 300, 100, 100);
}
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
if (++light_number >= 3)
light_number = 0;
repaint();
}
}
public class MyFrame extends JFrame {
public MyFrame() {
add(new MyPanel());
setSize(300, 500);
setVisible(true);
}
public static void main(String[] arg) {
new MyFrame();
}
}
12. (생략)
CHAPTER 16
중간점검문제
p.399
1. 이벤트가 발생한다.
2. 이벤트 처리기
3. 내부 클래스는 외부 클래스의 멤버에 접근할 수 있다.
Lab
1.
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import
import
import
import
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
class MyCounter extends JFrame implements ActionListener {
private JLabel label, label1;
private JButton button1, button2;
private int count = 0;
public MyCounter() {
JPanel panel = new JPanel();
label = new JLabel("Counter");
panel.add(label);
label1 = new JLabel("" + count);
label1.setFont(new Font("Serif", // 레이블에 폰트를 설정한다.
Font.BOLD | Font.ITALIC, 100));
panel.add(label1);
button1 = new JButton("카운터 증가");
panel.add(button1);
button1.addActionListener(this);
button2 = new JButton("카운터 감소");
panel.add(button2);
button2.addActionListener(this);
add(panel);
setSize(400, 200);
setTitle("My Counter");
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
if( event.getSource() == button1 ){
count++;
label1.setText(count + "");
}
else {
count--;
label1.setText(count + "");
}
}
}
public class CounterTest {
public static void main(String[] args) {
new MyCounter();
}
}
2. 도전 과제 중에서 1번만을 구현하였습니다.
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import
import
import
import
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
class MyCounter extends JFrame implements ActionListener {
private JLabel[] labels;
private JLabel score;
private JButton button;
private int[] numbers;
public MyCounter() {
setSize(500, 300);
JPanel panel = new JPanel();
panel.setLayout(null);
labels = new JLabel[3];
score = new JLabel("000");
numbers = new int[3];
for (int i = 0; i < 3; i++) {
labels[i] = new JLabel("" + numbers[i]);
labels[i].setFont(new Font("Serif", Font.BOLD
|
Font.ITALIC,
100));
labels[i].setSize(100, 100);
labels[i].setLocation(100 + 100 * i, 20);
panel.add(labels[i]);
}
button = new JButton("스핀");
button.setSize(250, 50);
button.setLocation(100, 150);
panel.add(button);
score.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 30));
score.setSize(250, 50);
score.setLocation(100, 200);
panel.add(score);
button.addActionListener(this);
add(panel);
setTitle("My Game");
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < 3; i++) {
numbers[i] = (int) (Math.random() * 10);
labels[i].setText("" + numbers[i]);
}
if(
labels[0].getText().equals(labels[1].getText())
labels[0].getText().equals(labels[2].getText()) )
score.setText("100");
else
score.setText("000");
}
}
&&
public class CounterTest2 {
public static void main(String[] args) {
new MyCounter();
}
}
Exercise
1.
(1)
(2)
(3)
(4)
(5)
참
참
거짓 - 마우스가 움직였을 때 발생하는 이벤트는 MouseMotionEvent이다
거짓 - 어댑터 클래스를 사용하면 원하는 메소드만을 구현하는 것이 가능해짐
거짓 - getKeyChar()는 문자를 반환한다. getKeyCode()를 사용해야 시프트키를 검출할 수
있다.
2. JButton b = new JButton("test");
b.addActionListener(new MyListener());
3. keyPressed() -> keyTyped() -> KeyReleased()
4.
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
img_x = e.getX();
img_y = e.getY();
repaint();
}
});
5.
class MyFrame extends JFrame {
JButton button;
public MyFrame() {
button = new JButton("버튼을 누르시오");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
System.out.println("마침내 버튼이 눌려졌습니다.");
}
});
}
}
6.
class MyFrame extends JFrame {
JButton button;
public MyFrame() {
button = new JButton("버튼을 누르시오");
button.addActionListener(new MyListener());
}
private class MyListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent arg0) {
System.out.println("마침내 버튼이 눌려졌습니다.");
}
}
}
Programming
1.
import java.awt.event.*;
import javax.swing.*;
class Myframe extends JFrame
{
JButton button;
JTextField t1;
JTextField t2;
public Myframe()
{
setSize(250,120);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("마일을 킬로미터로 변환");
JPanel panel1=new JPanel();
JLabel label=new JLabel("거리를 마일 단위로 입력하시오");
t1=new JTextField(5);
t2=new JTextField(20);
button=new JButton("변환");
button.addActionListener(new MyListener());
t1.setText("1");
t2.setEditable(false);
panel1.add(label);
panel1.add(t1);
panel1.add(button);
panel1.add(t2);
this.add(panel1);
setVisible(true);
}
private class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
int t=Integer.parseInt(t1.getText());
double k=t*1.609344;
t2.setText(t+" 마일은 "+k+" 킬로미터입니다.");
}
}
}
}
public class Pro1 {
public static void main(String[] arge)
{
Myframe f=new Myframe();
}
}
2.
import java.awt.event.*;
import javax.swing.*;
class Myframe extends JFrame
{
JButton button;
JTextField t1;
JTextField t2;
JTextField t3;
public Myframe()
{
setSize(230,150);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("이자 계산기");
JPanel panel1=new JPanel();
JLabel label1=new JLabel("원금을 입력하시오");
JLabel label2=new JLabel("이율을 입력하시오");
t1=new JTextField(5);
t2=new JTextField(5);
t3=new JTextField(15);
button=new JButton("변환");
button.addActionListener(new MyListener());
t3.setEditable(false);
panel1.add(label1);
panel1.add(t1);
panel1.add(label2);
panel1.add(t2);
panel1.add(button);
panel1.add(t3);
this.add(panel1);
setVisible(true);
}
private class MyListener implements ActionListener{
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==button)
{
int t=Integer.parseInt(t1.getText());
float a=Float.parseFloat(t2.getText());
int k=(int)(t*(a/100));
t3.setText("이자는 연 "+k+"만원 입니다.");
}
}
}
}
public class Pro2 {
public static void main(String[] arge)
{
Myframe f=new Myframe();
}
}
3.
---------------------------------------------------------------//이항 연산을 표현하는 클래스
public class DyadicOperation {
private double operandX;
private double operandY;
private char operator;
//생성자
public DyadicOperation(){
init();
}
//초기화
public void init(){
setOperandX(0);
setOperandY(0);
setOperator('=');
}
//접근자
public double getOperandX() {return operandX;}
public double getOperandY() {return operandY;}
public char getOperator() {return operator;}
//설정자
public void setOperandX(double operandX) {this.operandX = operandX;}
public void setOperandY(double operandY) {this.operandY = operandY;}
public void setOperator(char operator) {this.operator = operator;}
//식 입력(피연산자 일때)
public void inputFomula(double operand){
if(operator == '='){
setOperandX(operand);
setOperandY(operand);
}
else{
setOperandY(operand);
}
}
//식 입력(연산자 일때)
public boolean inputFomula(char operator){
if(operator != '=' && operator != '%'){
if(getOperator() != '='){
calculate();
setOperator(operator);
return true;
}
else{
setOperator(operator);
return false;
}
}
else if(operator == '=' && getOperator() != '='){
calculate();
return true;
}
else if(operator == '%' && getOperator() == '*'){
setOperandX(getOperandX()*getOperandY()*0.01);
return true;
}
return false;
}
//연산
public void calculate(){
switch(getOperator()){
case '+':
setOperandX(getOperandX() + getOperandY());
break;
case '-':
setOperandX(getOperandX() - getOperandY());
break;
case '*':
setOperandX(getOperandX() * getOperandY());
break;
case '/':
setOperandX(getOperandX() / getOperandY());
break;
}
}
}
------------------------------------------------------------------------------------------------------------------------------import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import
import
import
import
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.JTextField;
//계산기를 구현 하는 클래스
public class MyCalculator extends JFrame {
private JTextField f;//텍스트 필드
private boolean resultPrint;//결과 출력 상태
private DyadicOperation operation;//이항 연산 클래스
private Real num;//실수
//생성자
public MyCalculator(){
//슈퍼 클래스 생성자 명시적 호출을 통한 프레임 제목 설정
super("MyCalculator");
f = new JTextField("0.");//텍스트 필드
setResultPrint(false);//결과 출력 상태
operation = new DyadicOperation();//이항 연산 클래스
num = new Real();//실수
//메인 패널로 사용할 패널을 생성
JPanel mainPanel = new JPanel();
//flow, border, grid 중 텍스트 필드와 키패널의 비대칭적 크기를 고려해
border 선택
mainPanel.setLayout(new BorderLayout(10,10));
//텍스트 필드 생성 및 추가
f.setHorizontalAlignment(JTextField.RIGHT);
f.setEditable(false);
f.setBackground(Color.WHITE);
mainPanel.add(f,BorderLayout.NORTH);
//키패널 생성 및 추가
JPanel mainKeyPanel = new JPanel();
mainKeyPanel.setLayout(new BorderLayout(10,10));
KeyPanel1 keyPanel1 = new KeyPanel1();
KeyPanel2 keyPanel2 = new KeyPanel2();
mainKeyPanel.add(keyPanel1,BorderLayout.NORTH);
mainKeyPanel.add(keyPanel2,BorderLayout.CENTER);
mainPanel.add(mainKeyPanel,BorderLayout.CENTER);
//메인 패널을 프레임에 추가
add(mainPanel);
//flow, border, grid 중 프레임과 메인 패널 사이에 적절한 공간을 줄 수 있
는 flow 선택
setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setResizable(false);
setVisible(true);
}
//키패널 클래스 1
class KeyPanel1extends JPanel{
public KeyPanel1(){
//flow, border, grid 중 버튼 정렬을 하기 가장 적합한 grid 선택
setLayout(new GridLayout(0,3,10,10));
String[] str = new String[]
{"Backspace", "CE", "C"};
JButton[] button = new JButton[str.length];
//Backspace, CE, C의 순서로 버튼이 추가 되도록 반복
for(int i=0; i<str.length; i++){
button[i] = new JButton(str[i]);
button[i].setBackground(Color.WHITE);
button[i].setForeground(Color.RED);
add(button[i]);
button[i].addActionListener(new MyActionListener1());
}
}
}
//액션 리스너1 클래스
class MyActionListener1 implements ActionListener{//내부 클래스
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="C"){//초기화
operation.init();
num.init();
}
else if(e.getActionCommand()=="CE"){//현재 입력한 값 초기화
num.init();
}
else{//BackSpace
num.backSpace();
}
f.setText(num.toString());
}
}
//키패널 클래스 2
class KeyPanel2extends JPanel{//내부 클래스
public KeyPanel2(){//생성자
//flow, border, grid 중 버튼 정렬을 하기 가장 적합한 grid 선택
setLayout(new GridLayout(0,5,10,10));
String[] str = new String[]
{"7", "8", "9", "/", "sqrt", "4", "5", "6", "*", "%",
"1", "2", "3", "-", "1/x", "0", "+/-", ".", "+", "="};
JButton[] button = new JButton[str.length];
//7, 8, 9, /, sqrt,4,5,6,*,%,1,2,3,-,
//1/x, 0, +/-, ., +, =의 순서로 버튼이 추가 되도록 반복
for(int i=0; i<str.length; i++){
button[i] = new JButton(str[i]);
add(button[i]);
button[i].setBackground(Color.WHITE);
button[i].addActionListener(new MyActionListener2());
}
button[3].setForeground(Color.RED);
button[8].setForeground(Color.RED);
button[13].setForeground(Color.RED);
button[18].setForeground(Color.RED);
button[19].setForeground(Color.RED);
}
}
//액션 리스너2 클래스
class MyActionListener2 implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {//내부 클래스
// TODO Auto-generated method stub
String str = e.getActionCommand();
if(str.length() == 1){//단문자 인 경우
switch(str.charAt(0)){
//이항 연산자인 경우
case '/':
case '*':
case '-':
case '+':
case '=':
case '%':
if(num.toString() != "0."){
operation.inputFomula(Double.parseDouble(num.toString()));
}
setResultPrint(operation.inputFomula(str.charAt(0)));
if(isResultPrint()){
num.setReal(operation.getOperandX());
f.setText(num.toString());
}
num.init();
break;
default:
num.inputAppend(str.charAt(0));
f.setText(num.toString());
break;
}
}
else{
if(str == "+/-"){
num.sign();
}
else if(str == "1/x"){
num.inverse();
}
else{
num.sqrt();
}
f.setText(num.toString());
}
}
}
//접근자
public boolean isResultPrint() {return resultPrint;}
//설정자
public void setResultPrint(boolean resultPrint) {this.resultPrint = resultPrint;}
public static void main(String[] args){
MyCalculator c=new MyCalculator();
}
}
4.
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Color;
java.awt.Graphics;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
import javax.swing.JButton;
import
import
import
import
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
javax.swing.JTextField;
class MyPanel extends JPanel
{
int x=250, y=30;
public void move(int dx) {
this.x += dx;
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.yellow);
g.setColor(Color.red);
g.fillRect(x, y, 10, 200);
}
}
class Myframe extends JFrame
{
MyPanel panel;
JPanel panel1;
JButton b1, b2;
public Myframe()
{
setSize(500,300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("박스움직이기");
panel=new MyPanel();
panel1=new JPanel();
b1=new JButton("왼쪽으로 이동");
b2=new JButton("오른쪽으로 이동");
panel1.add(b1);
panel1.add(b2);
add(panel, BorderLayout.CENTER);
add(panel1, BorderLayout.SOUTH);
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
panel.move(-10);
}});
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
panel.move(10);
}});
setVisible(true);
}
}
public class MyFrameTest {
public static void main(String[] arge)
{
Myframe f=new Myframe();
}
}
5.
import
import
import
import
java.awt.Font;
java.awt.event.MouseAdapter;
java.awt.event.MouseEvent;
java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
class Myframe extends JFrame
{
JLabel label;
public Myframe()
{
setSize( 700,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("박스움직이기");
label = new JLabel("Don't cry before you are hurt");
label.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 50));
label.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
super.mouseExited(arg0);
label.setText("Don't cry before you are hurt");
}
public void mouseEntered(MouseEvent arg0) {
label.setText("다치기도 전에 울지말라");
}
});
add(label);
setVisible(true);
}
}
public class MyFrameTest {
public static void main(String[] arge)
{
Myframe f=new Myframe();
}
}
CHAPTER 17
중간점검문제
p.436
1. 이미지를 ImageIcon 객체로 만들고 버튼 객체의 setIcon() 메소드를 사용한다.
2. ImageIcon image = new ImageIcon("sample.gif");
3. setIcon()
p.438
1. setSelected()
2. ItemStateChanged
3. isSelected()
p.442
1. JRadioButton, ButtonGroup
2. isSelected()
3. Border 객체를 인수로 setBorder() 메소드를 호출한다.
p.445
1.
2.
3.
4.
5.
JTextArea
JTextPane
getText()
setText()
selectAll()
p.450
1. ActionEvent
2. JPasswordField
3. Integer.paseInt(tf.getText());
p.455
1.
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
ta.appendText("I\'ve clicked");
}
});
2. appendText();
p.457
1. 스크롤 페인을 생성하고 텍스트 영역을 스크롤 페인에 넣는다. 스크롤 페인을 하나의 컨
테이너로 간주하면 된다.
2.
JScrollPane scroll = new JScrollPane(textArea,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYES,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
Lab
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener{
//MyFrame 클래스 정의 JFrame으로 부터
상속
private int sum, temp1, temp2, temp3;
//액션리스너 구현
private JButton order_button, cancle_button;
//컴포넌트와 컨테
이너 참조변수
private JPanel down_panel;
private JTextField text;
WelcomePanel welcom_panel = new WelcomePanel();
크기 패널 생성
TypePanel TypePanel = new TypePanel();
ToppingPanel ToppingPanel = new ToppingPanel();
SizePanel SizePanel = new SizePanel();
public MyFrame(){
//문구,
타입,
토핑,
//생성자 정의
this.setSize(400,400);
//프레임 크기 정의
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//종료 설정
this.setTitle("피자 주문");
//타이틀 초기화
this.order_button = new JButton("계산"); //주문 버튼 생성
this.order_button.addActionListener(this); //이벤트 처리 등록
this.cancle_button = new JButton("취소"); //취소 버튼 생성
this.cancle_button.addActionListener(this); //이벤트 처리 등록
this.text = new JTextField();
text.setEditable(false);
text.setColumns(6);
//텍스트 필드 생성
//수정 불가
//길이 6칸
down_panel = new JPanel();
down_panel.add(this.order_button);
//패널 생성
//주문 버튼 취소 버
튼 추가
down_panel.add(this.cancle_button);
down_panel.add(this.text);
//텍스트 필드 추가
this.setLayout(new BorderLayout());
//프레임
배치관리자
설정
this.add(welcom_panel,BorderLayout.NORTH);
this.add(down_panel,BorderLayout.SOUTH);
//웰컴 패널 북쪽
//버튼 패널 남
쪽
//사이즈 패널 동
this.add(SizePanel,BorderLayout.EAST);
쪽
this.add(TypePanel,BorderLayout.WEST);
this.add(ToppingPanel ,BorderLayout.CENTER);
//타입 패널 서쪽
//토핑 패널 중
앙
pack();
//사이즈 조절
this.setVisible(true);
//프레임 화면 표시
}
public void actionPerformed(ActionEvent e) {
//액션이벤
트 처리
if(e.getSource() == this.order_button){
//액션소스 검출 '주문 버튼
시
if(this.TypePanel.combo.isSelected()){
//라디오 버튼 검사
temp1 = 100;
//해당 라디오 버튼 눌렷을
경우
}
//각 라이오 버튼의 비용을 임
시저장
else if(this.TypePanel.potato.isSelected()){
temp1 = 200;
}
else if(this.TypePanel.bulgogi.isSelected()){
temp1 = 300;
}
//토핑 라디오 버튼 검
사
if(this.ToppingPanel.pepper.isSelected()){
temp2 = 400;
}
else if(this.ToppingPanel.cheese.isSelected()){
temp2 = 500;
}
else if(this.ToppingPanel.peperoni.isSelected()){
temp2 = 600;
}
else if(this.ToppingPanel.bacon.isSelected()){
temp2 = 700;
}
//사이즈 라디오 버튼
검사
if(this.SizePanel.samll.isSelected()){
temp3 = 1000;
}
else if(this.SizePanel.medium.isSelected()){
temp3 = 5000;
}
else if(this.SizePanel.large.isSelected()){
temp3 = 10000;
}
sum = temp1 + temp2 + temp3;
//총 가격 합계 저장
this.text.setText(""+sum);
//텍스트 필드 출력
}
if(e.getSource() == this.cancle_button){
//액션 소스가 취소 버튼일 경
우
temp1 = 0;
temp2 = 0;
temp3 = 0;
sum = 0;
this.text.setText(""+sum);
//전부 초기화 후 초기값 출력
}
}
class WelcomePanel extends JPanel{
private JLabel message;
//웰컴 패널 클래스 정의 JPanel 상속
//메세지 라벨 참조 변수
public WelcomePanel(){
//생성자
message = new JLabel("자바 피자에 오신것을 환영합니다.");
add(message);
//라벨을 생성후 객체에 추가
}
}
class TypePanel extends JPanel{
//타입 패널 정의 JPanel 상속
private JRadioButton combo,potato, bulgogi;
//라디오 버튼 정의
private ButtonGroup bg;
//버튼 그룹 정의
public TypePanel(){
setLayout(new GridLayout(3,1));
//생성자
//배치관리자 정의
combo = new JRadioButton("콤보",true);
potato = new JRadioButton("포테이토");
bulgogi = new JRadioButton("불고기");
//라디오 버튼 생성
bg = new ButtonGroup();
//버튼
그룹
정의후
묶기
bg.add(combo);
bg.add(potato);
bg.add(bulgogi);
setBorder(BorderFactory.createTitledBorder("종류"));
튼그룹 정리
//버
//객체에 라디오 버튼
add(combo);
추가
add(potato);
add(bulgogi);
}
}
//토핑 패널 정의 JPanel
class ToppingPanel extends JPanel{
상속
private JRadioButton pepper, cheese, peperoni, bacon;
//라디오버튼 참
조변수
//버튼 그룹 참조
private ButtonGroup bg;
변수
public ToppingPanel(){
setLayout(new GridLayout(4,1));
//생성자
//배치관리자 일렬
pepper = new JRadioButton("피망",true);
//라디오 버튼 생
성
cheese = new JRadioButton("치즈");
peperoni = new JRadioButton("페페로니");
bacon = new JRadioButton("베이컨");
bg = new ButtonGroup();
//버튼 그룹 생성 후 라디오 버튼
묶기
bg.add(pepper);
bg.add(cheese);
bg.add(peperoni);
bg.add(bacon);
//버튼그룹 정리
setBorder(BorderFactory.createTitledBorder("추가토핑"));
//객체에 라디오 버튼
add(pepper);
추가
add(cheese);
add(peperoni);
add(bacon);
}
}
class SizePanel extends JPanel{
//사이즈 패널 정의 JPanel 상
속
private JRadioButton samll, medium, large;
//라디오 버튼 참조변
수
private ButtonGroup bg;
//버튼 그룹 참조변수
public SizePanel(){
setLayout(new GridLayout(3,1));
samll = new JRadioButton("Small",true);
medium = new JRadioButton("Medium");
large = new JRadioButton("Large");
//생성자
//배치관리자
//라디오 버튼 생성
bg = new ButtonGroup();
bg.add(samll);
bg.add(medium);
bg.add(large);
//버튼 그룹 생성
//버튼 그룹 정리
setBorder(BorderFactory.createTitledBorder("크기"));
add(samll);
add(medium);
add(large);
//객체에 라디오 버튼 추가
}
}
}
public class exam1 {
public static void main(String[] args) {
MyFrame mf = new MyFrame();
}
}
Exercise
1. (1) 참
(2) 참
(3) 거짓
(4) 참
(5) 거짓
(6) 거짓
2.
ImageIcon image = new ImageIcon("image.gif");
//드라이버 클래스
JLabel label = new JLabel("이미지 레이블");
label.setIcon(image);
3.
(1)
(2)
(3)
(4)
(5)
tf.getText()
tf.setText("");
ActionEvent가 발생한다.
ItemEvent
ActionEvent가 발생한다.
4.
(1)
(2)
(3)
(4)
JButton button= newJButton();
JTextField aTextField = new JTextField("초기텍스트", 20);
JTextComponent t = new JTextArea(20, 10);
JTextArea textArea = new JTextArea(20, 30);
new JScrollPane().add(textArea);
(5) panel.setBorder( BorderFactory.createTitledBorder("크기"));
Programming
1.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NumberGameextends JFrame {
private int randomNum;
private JTextField inputField;
private JLabel guideLabel;
private JButton retryButton;
private JButton exitButton;
public NumberGame(){
//부모 클래스 생성자 명시적 호출
super("숫자게임");
//top 패널에 들어갈 컴포넌트 구성
JLabel infoLabel = new JLabel("숫자를 추측하시오 : ");
inputField = new JTextField(10);
inputField.addActionListener(new TextFieldActionListener());
//top 패널 구성
JPanel topPanel = new JPanel();
topPanel.add(infoLabel);
topPanel.add(inputField);
//middle 패널에 들어갈 레이블 구성
guideLabel = new JLabel("숫자를 입력하시오.");
guideLabel.setBackground(Color.WHITE);
guideLabel.setOpaque(true);//레이블을 불투명하게
//middle 패널 구성
JPanel middlePanel = new JPanel();
middlePanel.add(guideLabel);
//low 패널에 들어갈 버튼 구성
retryButton = new JButton("새 게임");
exitButton = new JButton("종료");
retryButton.addActionListener(new ButtonActionListener());
exitButton.addActionListener(new ButtonActionListener());
//low 패널 구성
JPanel lowPanel = new JPanel();
lowPanel.add(retryButton);
lowPanel.add(exitButton);
//메인 패널 구성
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(topPanel);
mainPanel.add(middlePanel);
mainPanel.add(lowPanel);
add(mainPanel);
//랜덤 넘버와 프레임 설정
setRandomNum();
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
//TextField에 들어갈 액션 리스너
private class TextFieldActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
try{
if(Integer.parseInt(inputField.getText()) < randomNum){
guideLabel.setText("너무 낮습니다!");
guideLabel.setBackground(Color.RED);
}
else if(Integer.parseInt(inputField.getText()) > randomNum){
guideLabel.setText("너무 높습니다!");
guideLabel.setBackground(Color.RED);
}
else{
guideLabel.setText("정답입니다!");
guideLabel.setBackground(Color.WHITE);
}
}
catch(NumberFormatException ne){
guideLabel.setText("잘못된 입력입니다!");
guideLabel.setBackground(Color.RED);
}
inputField.selectAll();
}
}
//Button에 들어갈 액션 리스너
private class ButtonActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == retryButton){
setRandomNum();
guideLabel.setText("숫자를 입력하시오.");
inputField.setText("");
}
else if(e.getSource() == exitButton){
System.exit(0);
}
}
}
//접근자
public int getRandomNum() {return randomNum;}
//설정자
public void setRandomNum() {randomNum = (int)(Math.random()*100)+1;}
public static void main(String[] args){
new NumberGame();
}
}
2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TextConverter extends JFrame {
JButton converter;
JButton canceler;
JTextArea textIn;
JTextArea textOut;
public TextConverter(){
super("텍스트 변환");
//텍스트 에어리어
textIn = new JTextArea(10, 14);
textOut = new JTextArea(10, 14);
textIn.setLineWrap(true);//자동 줄바꿈
textOut.setLineWrap(true);
textOut.setEnabled(false);//비활성화
//텍스트 에어리어를 관리할 패널
JPanel textAreaPanel = new JPanel(new GridLayout(1, 2, 20, 20));
textAreaPanel.add(textIn);
textAreaPanel.add(textOut);
//버튼
converter = new JButton("변환");
canceler = new JButton("취소");
converter.addActionListener(new ButtonActionListener());
canceler.addActionListener(new ButtonActionListener());
//버튼 패널
JPanel buttonPanel = new JPanel(new FlowLayout());
buttonPanel.add(converter);
buttonPanel.add(canceler);
//메인 패널
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.add(BorderLayout.CENTER, textAreaPanel);
mainPanel.add(BorderLayout.SOUTH, buttonPanel);
//프레임 설정
setLayout(new FlowLayout(FlowLayout.CENTER, 20, 20));
add(mainPanel);
pack();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
//버튼의 액션 이벤트를 처리 할 버튼 액션 리스너 클래스
private class ButtonActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == converter){
textOut.setText("");
String result = toEnglish(textIn.getText());
textOut.append(result);
}
if(e.getSource() == canceler){
textOut.setText("");
}
}
//영어를 한국어로 변환하는 메소드
private String toEnglish(String korean){
String result = korean;
result = result.replace("텍스트", "Text");
result = result.replace("영어", "English");
return result;
}
}
public static void main(String[] args){
TextConverter t=new TextConverter();
}
}
3.
import
import
import
import
java.awt.Font;
java.awt.GridLayout;
java.awt.event.ItemEvent;
java.awt.event.ItemListener;
import
import
import
import
import
import
javax.swing.ImageIcon;
javax.swing.JCheckBox;
javax.swing.JComponent;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JPanel;
public class CheckBoxDemo extends JPanel implements ItemListener {
JCheckBox[] buttons = new JCheckBox[4];
String[] fruits = { "엔진오일 교환", "자동변속기오일교환", "에어콘필터교환", "타이
어 교환"};
int[] prices = { 45000, 80000, 30000, 100000 };
int money=0;
JLabel label;
public CheckBoxDemo() {
super();
// 체크 박스 생성
for (int i = 0; i < 4; i++) {
buttons[i] = new JCheckBox(fruits[i]);
buttons[i].addItemListener(this);
}
for (int i = 0; i < 4; i++)
add(buttons[i]);
label = new JLabel("현재까지의 가격은"+money+"입니다.");
label.setFont(new Font("Serif",
// 레이블에 폰트를 설정한다.
Font.BOLD | Font.ITALIC, 30));
add(label);
}
/** 체크 박스의 아이템 이벤트를 처리한다. */
public void itemStateChanged(ItemEvent e) {
Object source = e.getItemSelectable();
for (int i = 0; i < 4; i++) {
if (source == buttons[i]) {
if (e.getStateChange() == ItemEvent.DESELECTED)
money -= prices[i];
else
money += prices[i];
label.setText("현재까지의 가격은"+money+"입니다.");
}
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("CheckBoxDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new CheckBoxDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setSize(500, 200);
frame.setVisible(true);
}
}
4. 생략(3번 문제와 유사)
5.
import
import
import
import
import
import
import
import
import
java.awt.Canvas;
java.awt.Color;
java.awt.Dimension;
java.awt.Graphics;
java.awt.event.MouseEvent;
java.awt.event.MouseListener;
java.util.Random;
javax.swing.JFrame;
javax.swing.JPanel;
class MyPanel extends JPanel
{
private static final int EMPTY = 0,X_PIECE = 1,O_PIECE = 2;
private
private
private
private
private
int[][] gameGrid = new int[3][3];
boolean xTurn;
Random random;
boolean gameRunning;
int gameResult;
public MyPanel()
{
setPreferredSize(new Dimension(256,256));
setBackground(Color.WHITE);
addMouseListener(new GameListener());
random = new Random();
clearGrid();
gameRunning = true;
}
private class GameListener implements MouseListener
{
public void mousePressed(MouseEvent e){}
public void mouseClicked(MouseEvent e)
{
int xPos = e.getPoint().x;
int yPos = e.getPoint().y;
if(xPos > 50 && yPos > 50 && xPos < 50+50*3 && yPos <
50+50*3)
{
if(gameRunning == false)
{
clearGrid();
gameRunning = true;
repaint();
return;
}
if(gameGrid[xPos/50-1][yPos/50-1] != EMPTY)
return;
if(xTurn)
{
gameGrid[xPos/50-1][yPos/50-1] = X_PIECE;
xTurn = false;
}
else
{
gameGrid[xPos/50-1][yPos/50-1] = O_PIECE;
xTurn = true;
}
gameResult = gameOver();
if(gameResult != 0)
{
gameRunning = false;
}
repaint();
}
}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
}
public void clearGrid()
{
for(int y = 0;y < 3;y++)
for(int x = 0;x < 3;x++)
gameGrid[x][y] = EMPTY;
if(random.nextInt(100) < 50)
xTurn = true;
else
xTurn = false;
}
int gameOver()
{
for(int x = 0;x < 3;x++)
if(gameGrid[x][0] == gameGrid[x][1] && gameGrid[x][1]
gameGrid[x][2])
return gameGrid[x][0];
for(int y = 0;y < 3;y++)
if(gameGrid[0][y] == gameGrid[1][y] && gameGrid[1][y]
gameGrid[2][y])
return gameGrid[0][y];
if(gameGrid[0][0]
==
gameGrid[1][1]
&&
gameGrid[1][1]
gameGrid[2][2])
return gameGrid[0][0];
if(gameGrid[2][0]
==
gameGrid[1][1]
&&
gameGrid[0][2]
gameGrid[1][1])
return gameGrid[2][0];
for(int y = 0;y < 3;y++)
for(int x = 0;x < 3;x++)
if(gameGrid[x][y] == 0)
return 0;
return 3;
}
public void paintComponent(Graphics g)
{
g.clearRect(0,0,getWidth(),getHeight());
g.setColor(Color.BLACK);
for(int y = 1;y < 3;y++)
g.drawLine(50,y*50+50,50+50*3,y*50+50);
for(int x = 1;x < 3;x++)
g.drawLine(x*50+50,50,x*50+50,50+50*3);
for(int y = 0;y < 3;y++)
{
for(int x = 0;x < 3;x++)
{
if(gameGrid[x][y] == X_PIECE)
{
g.setColor(Color.BLUE);
g.drawLine(50+x*50,50+y*50,50+x*50+50,50+y*50+50);
g.drawLine(50+50+x*50,50+y*50,50+x*50,50+y*50+50);
}
==
==
==
==
if(gameGrid[x][y] == O_PIECE)
{
g.setColor(Color.RED);
g.drawOval(50+x*50,50+y*50,50,50);
}
}
}
g.setColor(Color.BLACK);
if(gameRunning)
{
if(xTurn)
g.drawString("X 차례입니다.",10,220);
else
g.drawString("O 차례입니다.",10,220);
}
else
{
if(gameResult == X_PIECE)
g.drawString("X가 이겻습니다!",10,220);
if(gameResult == O_PIECE)
g.drawString("O가 이겼습니다!",10,220);
if(gameResult == 3)
g.drawString("비겼습니다!",10,220);
g.drawString("새로운 게임을 시작하려면 클릭하세요.",10,240);
}
}
}
public class TicTacToeGame extends JFrame
{
public static void main(String[] args)
{
TicTacToeGame ticTacToe = new TicTacToeGame();
ticTacToe.setTitle("tic-tac-toe");
ticTacToe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MyPanel gameBoard = new MyPanel();
ticTacToe.add(gameBoard);
ticTacToe.pack();
ticTacToe.setLocationRelativeTo(null);
ticTacToe.setVisible(true);
}
}
6.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Login extends JFrame implements ActionListener {
JButton SUBMIT;
JPanel panel;
JLabel label1, label2;
final JTextField text1, text2;
Login() {
label1 = new JLabel();
label1.setText("이메일");
text1 = new JTextField(30);
label2 = new JLabel();
label2.setText("비밀번호");
text2 = new JPasswordField(30);
SUBMIT = new JButton("로그인");
panel = new JPanel(new GridLayout(0, 1));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(SUBMIT);
add(panel, BorderLayout.CENTER);
SUBMIT.addActionListener(this);
setTitle("LOGIN FORM");
}
public void actionPerformed(ActionEvent ae) {
String value1 = text1.getText();
String value2 = text2.getText();
if (value1.equals("hong") && value2.equals("1111")) {
System.out.println("로그인 성공");
} else {
System.out.println("로그인 실패");
}
}
}
public class LoginDemo {
public static void main(String arg[]) {
Login frame = new Login();
frame.setSize(400, 200);
frame.setVisible(true);
}
}
CHAPTER 18
중간점검문제
p.6
1. list.setBorder(BorderFactory.createLineBorder(Color.black, 1));
2.
ListSelectionModel.SINGLE_SELECTION
ListSelectionModel.SINGLE_INTERVAL_SELECTION
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
예를 들어서 단일 선택 모드로 변경하려면 다음과 같은 문장을 사용한다.
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
p.10
1. combo.addItem("dog");
2. ActionEvent
3. getSelectedItem()
p.13
1. SpinnerListModel, SpinnerNumberModel, SpinnerDateModel
2. 적합한 값들만 입력받는다.
p.16
1. ChangeEvent
2. getValue()
p.19
1. add()
2. TreeSelectionEvent
3. getUserObject()
Exercise
1.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener {
JTextField tf1=new JTextField(10);
JTextField tf2=new JTextField(10);
JTextField tf3=new JTextField(10);
JButton b=new JButton("입력");
public MyFrame() {
JPanel panel1 = new JPanel();
panel1.add(new JLabel("중간고사"));
panel1.add(tf1);
panel1.add(new JLabel("기말고사"));
panel1.add(tf2);
JPanel panel2 = new JPanel();
panel2.add(b);
JPanel panel3 = new JPanel();
panel3.add(new JLabel("총점은"));
panel3.add(tf3);
panel3.add(new JLabel("입니다."));
add(panel1, BorderLayout.NORTH);
add(panel2, BorderLayout.CENTER);
add(panel3, BorderLayout.SOUTH);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
String value1 = tf1.getText();
String value2 = tf2.getText();
int mid_s = Integer.parseInt(value1);
int final_s = Integer.parseInt(value2);
tf3.setText(""+(mid_s+final_s));
}
}
public class MyFrameTest {
public static void main(String arg[]) {
MyFrame frame = new MyFrame();
frame.setSize(400, 150);
frame.setVisible(true);
}
}
2.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Chapter21_Frameextends JFrame{
//
클래스안에 공통으로 사용될 필드
String[] petStrings={"Bird","Cat","Dog","Robbit","Pig"}; //
하는 배열
리스트의 목록을 저장
//
프레임의 설정과 컴포넌트를 불러오는 생성자
public Chapter21_Frame()
{
Com C=new Com();
//
콤보박스와 그림을 배치하고, 이벤트를 처리하는
객체 선언
setTitle("Chapter21");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
C.Panel1();
C.Panel2();
//
//
콤보박스를 배치하는 매서드 호출
그림을 배치하는 매서드 호출
pack();
setVisible(true);
}
class Com implements ActionListener{
JComboBox petList;
//
목록을 선택할 콤보박스
JLabel label;
//
사진이 들어갈 레이블
public void Panel1()
{
JPanel Pan=new JPanel();
petList=new JComboBox(petStrings);
//
리스트의 목록으로 콤보박스객
체를 생성한다.
petList.setSelectedIndex(4);
//
콤보박스의 기본적인 선택값은 리스트의
5번째로 한다.
petList.addActionListener(this);
//
콤보박스에서 이벤트가 발생하면 현재
클래스 안의 액션리스너로 이벤트를 처리
Pan.add(petList);
add(Pan,BorderLayout.PAGE_START);
}
public void Panel2()
{
JPanel Pan=new JPanel();
label=new JLabel();
//
스크롤을 항상 보이게 생성한다.
JScrollPane
scroll=new
JScrollPane(label,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCRO
LLBAR_ALWAYS);
label.setIcon(new ImageIcon(petStrings[4]+".jpg")); //
레이블에서
리스트의
5번째와 같은 이름의 이미지를 출력한다.
Pan.add(scroll);
add(Pan,BorderLayout.PAGE_END);
}
public void actionPerformed(ActionEvent e)
{
JComboBox cb=(JComboBox)e.getSource();
String petName=(String)cb.getSelectedItem();
//
이벤트 발생시 받아온
매개변수를 문자열로 변환한다.
updateLabel(petName); //
변환한 문자열을 매개변수로 레이블의 그림을 바
꿔주는 매서드를 호출한다.
}
void updateLabel(String petName)
{
label.setIcon(new ImageIcon(petName+".jpg"));
//
이미지를
매개변수와
같은 이름의 이미지로 교체한다.
}
}
}
class Chapter21 {
public static void main(String[] args)
{
Chapter21_Frame Chapter21_F=new Chapter21_Frame();
}
}
(1)
import
import
import
import
java.awt.BorderLayout;
javax.swing.*;
javax.swing.event.ListSelectionEvent;
javax.swing.event.ListSelectionListener;
class Chapter21_Frameextends JFrame{
//
클래스안에 공통으로 사용될 필드
String[] petStrings={"Bird","Cat","Dog","Robbit","Pig"}; //
하는 배열
리스트의 목록을 저장
//
프레임의 설정과 컴포넌트를 불러오는 생성자
public Chapter21_Frame()
{
Com C=new Com();
//
리스트와 그림을 배치하고, 이벤트를 처리하는
객체 선언
setTitle("Chapter21");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
C.Panel1();
C.Panel2();
//
//
리스트를 배치하는 매서드 호출
그림을 배치하는 매서드 호출
pack();
setVisible(true);
}
class Com implements ListSelectionListener{
JList petList;
//
목록을 선택할 리스트
JLabel label;
//
사진이 들어갈 레이블
public void Panel1()
{
JPanel Pan=new JPanel();
petList=new JList(petStrings);
//
리스트의 목록으로 리스트객체를 생성한
다.
petList.setSelectedIndex(4);
//
리스트의 기본적인 선택값은 리스트의
5번째로 한다.
petList.addListSelectionListener(this);
//
리스트에서 이벤트가 발생하면
현재 이벤트를 처리
Pan.add(petList);
add(Pan,BorderLayout.PAGE_START);
}
public void Panel2()
{
JPanel Pan=new JPanel();
label=new JLabel();
//
스크롤을 항상 보이게 생성한다.
JScrollPane
scroll=new
JScrollPane(label,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCRO
LLBAR_ALWAYS);
label.setIcon(new ImageIcon(petStrings[4]+".jpg")); //
레이블에서
리스트의
5번째와 같은 이름의 이미지를 출력한다.
Pan.add(scroll);
add(Pan,BorderLayout.PAGE_END);
}
public void valueChanged(ListSelectionEvent e)
{
JList cb=(JList)e.getSource();
String petName=(String)cb.getSelectedValue();
//
이벤트 발생시 받아온
매개변수를 문자열로 변환한다.
updateLabel(petName); //
변환한 문자열을 매개변수로 레이블의 그림을 바
꿔주는 매서드를 호출한다.
}
void updateLabel(String petName)
{
label.setIcon(new ImageIcon(petName+".jpg"));
//
이미지를
매개변수와
같은 이름의 이미지로 교체한다.
}
}
}
class Chapter21 {
public static void main(String[] args)
{
Chapter21_Frame Chapter21_F=new Chapter21_Frame();
}
}
CHAPTER 19
문제가 없음!
CHAPTER 20
중간점검문제
p.476
1. 관련있는 클래스를 서로 묶기 위하여
2. 디폴트 패키지에 자동으로 속하게 된다.
p.478
1.
(1) graphics.Rectangle라고 적어준다.
(2) import graphics.Rectangle;를 소스 파일의 첫 부분에 추가한다.
(3) import graphics.*;를 소스 파일의 첫 부분에 추가한다.
2. 인터넷 도메인 이름의 역순으로 하는 것이 좋다.
p.482
1. 관련된 클래스들을 묶을 수 있고, 기능에 따라 클래스를 패키지로 분류할 수 있고, 같은
클래스 이름을 여러 패키지가 사용할 수 있고, 패키지 별로 접근에 제약을 가할 수 있다.
2. 인터넷 도메인 이름의 역순으로 하는 것이 좋다.
3. kr.ac.hu.xxx
4. (작업 디렉토리)/company/project/
5. package project.server;
6. javac에서 -d 옵션을 사용한다.
p.483
1. Buffer,ByteBuffer,ByteOrder,CharBuffer,DoubleBuffer,FloatBuffer,IntBuffer,LongBuffer,
MappedByteBuffer,ShortBuffer 등의 클래스가 정의되어 있다.
p.490
1. 정수 10은 객체가 아니다. Integer(10)은 객체이다.
2. String클래스는 상수 문자열, 즉 변경이 불가능한 문자열을 나타낼 때 사용되고
StringBuffer는 내부적으로 문자열을 저장하는 메모리를 가지고 있어 변경 가능한 문자열
을 저장한다.
p.497
1.
Random random = new Random();
System.out.println(random.nextInt(999)+1);
2.
Date d = new Date();
System.out.println(d);
Exercise
1.
(1) package movie;
(2) movie.Director d = new movie.Director();
(3) import movie.*;
2.
(1) 각 파일의 첫 번째 줄에서 패키지를 지정하여야 한다.
Client.java:
package mysrc.client;
Server.java:
package mysrc.server;:
Utilities.java:
package mysrc.util;
(2)
먼저 mysrc 디렉토리 안에 client, server, util 디렉토리를 생성한다.
mysrc/client/ 안에 Client.java 파일을 위치시킨다.
mysrc/server/ 안에 Server.java 파일을 위치시킨다.
mysrc/util/ 안에 Utilities.java 파일을 위치시킨다.
(3)
예를 들어서 util 패키지를 사용하는 소스 파일이면 다음 중 하나의 방법을 선택한다.
import mysrc.util.*;
또는
import mysrc.shared.Utilities;
3.
(1)
Random random = new Random();
System.out.println(random.nextInt(9)+1);
(2)
import java.util.*;
public class Test{
public static void main(String[] args){
StringTokenizer st = new StringTokenizer("By doubting we come at the truth");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
}
}
(3)
import java.util.*;
public class Test{
public static void main(String[] args){
Calendar d = Calendar.getInstance();
System.out.print(d.get(Calendar.YEAR)+ "년 ");
System.out.print(d.get(Calendar.MONTH)+1+"월 ");
System.out.print(d.get(Calendar.DATE)-1+"일");
}
}
(4)
import java.util.Arrays;
public class Test{
public static void main(String[] args){
int[] array = {9,4,5,6,2,1};
Arrays.sort(array);
for(int i = 0; i < array.length; i++)
System.out.print(array[i]);
}
}
(5) int s = Integer.parseInt("12345");
(6) System.out.println(obj.class.getName());
4.
(1)
(2)
(3)
(4)
(5)
Calendar d = Calendar.getInstance();
오류 없음!(auto-boxing이 일어나게 됨)
Integer i = new Integer(100);
오류 없음!
오류 없음!
5.
public class Test {
public static void main(String[] args) {
________________________________;
}
}
(1) Random random = new Random();
System.out.println(random.nextInt(100));
(2) StringTokenizer st = new StringTokenizer("082-2-777-5566", "-");
while(st.hasMoreTokens()){
System.out.println(st.nextToken());
}
(3)
Calendar d = Calendar.getInstance();
System.out.println(d);
(4) Test obj = new Test();
System.out.println("The class of " + obj +
" is " + obj.getClass().getName());
(5)
for(int i = 0; i<= 90; i +=5) {
System.out.println(Math.sin(Math.toRadians((double)i)));
}
Programming
1.
package game;
import java.util.Random;
public class Die {
private int value;
private int num;
Random r = new Random();
public Die(){
value = 1;
}
public int roll(){
num = (r.nextInt(5)+1);
return num;
}
public void setValue(int v){
value = v;
}
public String toString(){
return ("현재 주사위 상태 : " + roll());
}
public static void main(String[] args){
Die d = new Die();
System.out.println(d.toString());
}
}
2.
package rps;
import java.util.*;
public class Game {
public static void main(String[] args){
Random r = new Random();
Scanner s = new Scanner(System.in);
int num1, num2;
System.out.println("하나를 선택하시요 : 가위(0), 바위(1), 보(2) :");
num1 = s.nextInt();
num2 = r.nextInt(3);
if(num2 == 0)
System.out.println("컴퓨터는 가위를 냈습니다.");
else if(num2 == 1)
System.out.println("컴퓨터는 바위를 냈습니다.");
else
System.out.println("컴퓨터는 보를 냈습니다.");
if(num1==0){
if(num2 == 1)
System.out.println("컴퓨터가 이겼습니다");
else if(num2 == 2)
System.out.println("당신이 이겼습니다.");
else
System.out.println("비겼습니다.");
}
else if(num1 == 1){
if(num2 == 0)
System.out.println("당신이 이겼습니다.");
else if(num2 == 2)
System.out.println("컴퓨터가 이겼습니다.");
else
System.out.println("비겼습니다.");
}
else{
if(num2 == 0)
System.out.println("컴퓨터가 이겼습니다");
else if(num2 == 1)
System.out.println("당신이 이겼습니다.");
else
System.out.println("비겼습니다.");
}
}
}
3.
import java.util.*;
import java.util.Arrays;
public class StrSort {
public static void main(String[] args){
Scanner s = new Scanner(System.in);
int count = 0, i = 0;
String[] ars = new String[100];
System.out.println("문자열을 입력하시요 : ");
String str = s.nextLine();
StringTokenizer st = new StringTokenizer(str);
while(st.hasMoreTokens()){
ars[i] = st.nextToken();
System.out.println(ars[i]);
count++;
i++;
}
System.out.println("모두 " + count + "개의 단어가 있습니다.");
Arrays.sort(ars);
StringTokenizer st2 = new StringTokenizer(str);
System.out.println("====== sort ======");
while(st2.hasMoreTokens()){
System.out.println(st2.nextToken());
}
}
}
CHAPTER 21
중간점검문제
p.512
1. 0으로 나누는 경우, 배열의 인덱스가 한계를 넘는 경우, 하드웨어 에러등
2. 프로그램에서 오류를 처리한 후에 계속 실행하는 것이 가능하다.
3.
int[] array = new int[10];
try{
array[11] = 0;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("배열의 범위를 벗어났습니다.");
}
4.
int[] array = new int[10];
try{
array[11] = 0;
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("배열의 범위를 벗어났습니다.");
}
finally{
array = null;
}
p.516
1. Error는 시스템에서 발생하는 심각한 오류이고, RuntimeException은 프로그래밍 시에 흔
히 발생할 수 있는 일반적인 실행 오류를 나타낸다.
2. RuntimeException을 제외한 모든 Exception
3. RuntimeException은 프로그래머가 방지할 수 있다.
p.521
1. try/catch블록을 이용하여서 처리한다.
2. throws를 사용하여 메소드가 예외를 발생한다고 정의할 수 있다.
3. 메소드가 예외를 발생한다는 것을 의미한다.
p.524
1.
class DiskFailureException extends Exception{
public MyException()
{
super( "DiskFailure!" );
}
}
2.
class NegativeNumberException extends Exception{
public NegativeNumberException(){
super("음수는 입력할 수 없음");
}
}
...
int score;
int tot = 0;
try {
for(int i = 0; i < 3; i++){
score = scan.nextInt();
if(score < 0)
throw new NegativeNumberException();
tot += score;
}
System.out.println("평균은 " + tot/3.0 + "입니다.");
} catch(NegativeNumberException e) {
System.out.println(e.toString());
}
Lab
1.
(1)
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileErrorTest {
public static void main(String[] args) {
try {
Scanner in = new Scanner(new File("data.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
(2)
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class FileErrorTest {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(new File("data.txt"));
}
}
2.
import java.util.Scanner;
public class ExceptionTest {
public static void main(String[] args) {
int[] list;
int sum = 0, count;
try {
Scanner sc = new Scanner(System.in);
System.out.print("정수의 개수: ");
count = sc.nextInt();
list = new int[count];
for(int i=0; i<count; i++){
System.out.print("정수를 입력하시오: ");
list[i] = sc.nextInt();
}
for(int i=0;i<count; i++){
sum += list[i];
}
System.out.println("평균은 "+ sum/count);
}
catch (ArithmeticException e) {
e.printStackTrace();
}
catch (NegativeArraySizeException e) {
e.printStackTrace();
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
Exercise
오류와 발생되는 예외를 올바르게 짝지으시오.
int[] list; list[0] = 0; -> 컴파일 오류, 배열은 초기화되지 않았고 컴파일되지 않는다.
자바 가상 기계가 클래스를 찾을 수 없는 경우 -> error
파일을 읽던 프로그램이 파일의 끝에 도달한 경우 -> 예외가 아니다. 스트림을 읽을 때
는 언젠가는 스트림의 끝에 도달하리라는 것을 예상할 수 있다. 예외는 예상치 못한 경
우에 사용한다.
Ÿ 파일의 끝에 도달했는데도 파일을 읽으려고 시도 -> 체크 예외(checked exception)
1.
Ÿ
Ÿ
Ÿ
2.
try {
System.out.println(list[size]);
// 배열 list의 크기가 size라고 가정한다.
}
catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
3.
합법적인 코드이고 또한 대단히 유용하다. 만약 try 블록에 있는 코드가 오류가 발생되어서
여러 개의 출구 경로를 가진다고 가정하자. 하지만 finally 블록에 있는 코드는 어떠한 경우
에도 실행된다. 따라서 반드시 실행되어야 하는 코드는 finally 블록에 넣는 것이 좋다. 예
를 들어서 입출력 스트림을 닫는 코드가 여기에 해당한다.
4. 이 예외 처리기는 거의 모든 종류의 예외를 잡는다. 따라서 어떤 종류의 예외인지를 알
기가 힘들다.
5.
첫 번째 예외 처리기는 Exception 타입의 예외를 잡는다. 따라서 모든 종류의 예외는 잡는
다. 따라서 두 번째 예외 처리기는 실행되지 못한다.
6.
숫자형식오류
finally
7.
배열 크기 음수 오류
8.
(1)
(2)
(3)
(4)
java.lang.ArrayIndexOutOfBoundsException
java.lang.NullPointerException
java.lang.NumberFormatException: For input string: "abc"
java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Integer
Programming
1.
(1) java.lang.ArrayIndexOutOfBoundsException
(2)
try {
int i = array[10];
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
(3)
public static void sub() throws ArrayIndexOutOfBoundsException {
int[] array = new int[10];
int i = array[10];
}
2.
class MyException extends Exception {
public MyException(String message) { super(message);
}
}
public class MyExceptionTest {
public static void checkNegative(int number) throws MyException {
if (number < 0) {
throw (new MyException("음수는 안됩니다."));
}
System.out.println("다행히 음수가 아니군요");
}
public static void main(String[] args) {
try {
checkNegative(1);
checkNegative(-1);
} catch (MyException ex) {
ex.printStackTrace();
}
}
}
3.
import java.util.Scanner;
class NotFoundExecption extends Exception{
public NotFoundExecption()
{
super("배열에서 찾을 수 없습니다.");
}
}
public class Lab2 {
public static int searchArray(int array[], int data) throws NotFoundExecption
{
for(int i=0;i<array.length;i++){
if( array[i] == data )
return i;
}
throw new NotFoundExecption();
}
public static void main(String[] arge)
{
Scanner sc=new Scanner(System.in);
int[] a={0,1,2,3,4,5,6,7,8,9};
int data=sc.nextInt();
try {
searchArray(a, data);
} catch (NotFoundExecption e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
4.
import java.util.Scanner;
class NegativeBalanceException extends Exception
{
public NegativeBalanceException(String message)
{
super(message);
}
}
class BankAccount
{
private int balance=0;
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public void deposit(int amount)
{
balance += amount;
}
public void withdraw(int amount) throws NegativeBalanceException
{
if( balance < amount )
throw new NegativeBalanceException("잔고가 음수입니다.");
balance -= amount;
}
}
public class BankAccountTest {
public static void main(String[] arge)
{
BankAccount ba = new BankAccount();
ba.deposit(100);
try {
ba.withdraw(200);
} catch (NegativeBalanceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
NegativeBalanceException: 잔고가 음수입니다.
at BankAccount.withdraw(BankAccountTest.java:25)
at BankAccountTest.main(BankAccountTest.java:35)
CHAPTER 22
중간점검문제
p.539
1. 참조되는 데이터의 정확한 타입을 알 수 없기 때문이다.
2. Box<Rectangle> b = new Box<Rectangle>();
3.
class Point<T> {
private T x;
private T y;
public T getY() {
return y;
}
public T getX() {
return x;
}
public void setX(T x)
{
this.x = x;
}
public void setY(T y)
{
this.y = y;
}
}
p.540
1.
public <T> void sub(T d)
{
...
}
2.
public class Test
{
public static <T> void displayArray(T[] a)
{
if (a == null || a.length == 0)
return;
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static void main(String[] args) {
Integer[] a = { 1, 2, 3, 4, 5};
Test.<Integer>displayArray(a);
}
}
p.547
1. 리스트(list), 스택(stack), 큐(queue), 집합(set), 해쉬 테이블(hash table)
2. 프로그램에서 자료들을 저장할 때 사용한다.
p.548
1.
p.553
1. 크기가 고정되어 있지 않다.
2. List 인터페이스
3. 컬렉션 객체들이 인터페이스를 구현하였기 때문이다.
4.
* 일반적인 for 루프
* for-each 루프
* 반복자 사용
p.556
1. ArrayList는 근본적으로 배열을 사용한다. LinkedList는 연결 리스트를 사용한다.
2. 리스트의 중간에 삽입이나 삭제가 많은 경우
p.560
1. 중복을 허용하지 않으면서 항목들의 리스트가 필요한 애플리케이션
2. Set은 항목들의 중복을 서용하지 않는다. List는 항목들의 중복을 허용한다.
p.566
1. 키(key), 값(value)
2.
put(): 데이터를 저장한다.
get(): 데이터를 꺼내온다.
p.571
1. 배열을 생성한 후에 배열을 가지고 List 객체를 만든다. 이 객체를 Collection의 정적 메
소드 sort()로 전달하면 된다.
2.
Exercise
1.
(1)
(2)
(3)
(4)
ArrayList<Double> list = new ArrayList<Double>();
컬렉션에 저장된 항목들을 순차적으로 방문할 때
리스트(list)는 중복을 허용하고 집합(set)은 중복을 허용하지 않는다.
Map
2.
* 자바 컴파일러는 컴파일 시간에 제네릭 코드에 대하여 타입을 검사할 수 있다.
* 제네릭을 이용하면 타입을 매개 변수처럼 간주할 수 있다.
* 제네릭을 이용하여서 제네릭 알고리즘을 구현할 수 있다.
3. > 연산자는 기초 자료형에만 적용된다.
4.
public final class MyAlgorithm {
public static <T> void swap(T[] a, int i, int j) {
T temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
5.
(1)
public class Stack <T> {
private T[] stack;
public void push(T data) { ... }
public T pop() { ... }
}
(2)
Stack<String> s = new Stack<String>();
6.
(1)
(2)
(3)
(4)
(5)
(6)
[사과, 배, 바나나, 포도]
[사과, 배, 자몽, 바나나, 포도]
바나나
[사과, 자몽, 바나나, 포도]
true
0
7.
(1)
for(int i=0;i<list.length;i++)
System.out.println(list[i]);
(2)
for(Double data; list)
System.out.println(data);
(3)
Iterator e = list.iterator();
while(e.hasNext())
{
d = (Double)e.next();
System.out.println(d);
}
// 반복자는 Object 타입을 반환!
Programming
1.
import java.util.*;
public class RandomList<T> {
Random r = new Random();
String[] sample = {"i", "walk", "the", "line"};
List<T> list = (List<T>) Arrays.asList(sample);
public void add(T item){
list.add(item);
}
public T select() {
int num = r.nextInt(list.size());
return list.get(num);
}
}
2. 평균을 구할 때 double형으로 변환하여 계산한다.
class MyMath<T> extends Number> {
double v=0.0;
public double getAverage(T[] a){
for (int i = 0; i < a.length; i++)
v = v + a[i].doubleValue();
return v/a.length;
}
}
public class Test
{
public static void main(String[] args) {
Integer[] list = { 1, 2, 3, 4, 5, 6 };
MyMath<Integer> m = new MyMath<Integer>();
System.out.println(m.getAverage(list));
}
}
3.
class MyPair<T> {
private T str1, str2;
public MyPair(T s1, T s2){
str1 = s1;
str2 = s2;
}
public void getStr1(T s1){
str1 = s1;
}
public void getStr2(T s2){
str2 = s2;
}
public T setStr1(){
return str1;
}
public T setStr2(){
return str2;
}
public String toString(){
return "str1 : " + str1 + " str2 : " + str2;
}
}
public class MyPairTest{
public static void main(String[] args){
MyPair<String> fruit = new MyPair<String>("사과", "포도");
System.out.println(fruit.toString());
}
}
4.
public class Test
{
public static <T> void displayArray(T a)
{
System.out.println(a.getClass().getName());
}
public static void main(String[] args) {
int x=0;
float y=0.0F;
Test.<Object>displayArray(x);
Test.<Object>displayArray(y);
}
}
java.lang.Integer
java.lang.Float
오토박싱에 의하여 int와 float가 Integer 객체와 Float 객체로 자동 변환된다.
5.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Test
{
public static void main(String[] args) {
ArrayList<Double> list = new ArrayList<Double>();
Scanner sc = new Scanner(System.in);
for(int i=0;i<10; i++){
System.out.print("심사위원의 점수: ");
double value = sc.nextDouble();
list.add(value);
}
double
double
double
double
for(int
max = Collections.max(list);
min = Collections.min(list);
sum = 0.0;
value = 0.0;
i=0;i<10; i++){
value = list.get(i);
if( value != min && value != max )
sum += value;
}
System.out.print("점수의 합: "+ sum);
}
}
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
심사위원의
점수의 합:
점수:
점수:
점수:
점수:
점수:
점수:
점수:
점수:
점수:
점수:
44.0
1
2
3
4
5
6
7
8
9
10
6.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
class Student implements Comparable<Student>
{
public Student(String name, String address, String phone) {
super();
this.name = name;
this.address = address;
this.phone = phone;
}
public int compareTo(Student s) {
return name.compareTo(s.name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Student [name=" + name + ", address=" + address + ", phone="
+ phone + "]";
}
String name;
String address;
String phone;
}
public class Test
{
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
Scanner sc = new Scanner(System.in);
for(int i=0;i<10; i++){
list.add(new Student("name"+i, "address"+i, "phone"+i));
}
Collections.sort(list);
int pos = Collections.binarySearch(list, new Student("name3", "address3",
"phone3"));
System.out.println(pos);
}
}
3
7. 문제 오타:
로또 번호를 생성하는 프로그램을 작성하여 보자. 로또는 1부터 45까지의 숫자 중에서 6개
를 선택한다. 로또 번호는 중복되면 안 된다. 따라서 집합을 나타내는 HashSet을 사용하여
서 중복을 검사하여 보자. Math.random()을 사용하면 0부터 1사이의 난수를 생성할 수 있
다. 0부터 1사이의 난수가 생성되면 여기에 44를 곱하고 1을 더하면 1부터 45사이의 정수
를 생성할 수 있다. 생성된 정수는 HashSet의 contains() 메소드를 이용하여서 이미 선택된
정수인지를 검사한다.
import java.util.HashSet;
public class Lotto {
@Override
public String toString() {
return "Lotto [set=" + set + "]";
}
HashSet<Integer> set = new HashSet<Integer>();
public Lotto() {
int d;
for (int i = 0; i < 6; i++) {
do {
d = (int) (Math.random() * 44.0 + 1.0);
} while (set.contains(d));
set.add(d);
}
}
public static void main(String[] args) {
Lotto lotto = new Lotto();
System.out.println(lotto);
}
}
Lotto [set=[16, 23, 7, 8, 26, 30]]
CHAPTER 23
중간점검문제
p.582
1. 프로세스는 독자적으로 실행이 가능한 환경으로 일반적으로 완전한 자기만의 자원을 가진
다. 스레드는 프로세스 안에 존재하여 프로세스의 자원을 공유한다.
2. 게임 프로그램
3. 데이터를 공유하기 때문에 동기화 문제가 발생한다.
p.588
1. Thread
2. 자바에서는 단일 상속만 가능하므로 다른 클래스를 이미 상속한 클래스는 스레드로 만들
수 없다.
p.593
1. setPriority()는 현재 스레드의 우선 순위를 변경하고 getPriority()는 현재 스레드의 우선순
위를 반환한다.
2. 현재 스레드의 실행을 지정된 시간 동안 중단하게 만든다
3. 현재 수행 가능한 스레드 중에서 가장 우선 순위가 높은 스레드를 먼저 실행시킨다.
4. run() 메소드 안에 스레드가 해야 할 작업을 서술한다.
5. start()메소드를 호출하면 run()이 호출된다. stop() 메소드를 사용하여 스레드를 정지시켜
종료한다.
6. 다른 스레드가 suspend()를 호출하는 경우, 스레드가 wait()를 호출하는 경우, 스레드가
sleep()을 호출하는 경우, 스레드가 입출력 작업을 하기 위해 대기하는 경우
p.599
1. 공유된 데이터를 여러 개의 스레드가 동시에 접근하기 때문에 발생한다.
2. synchronized
p.599
1. 스레드 간의 동작을 일치하기 위하여 사용한다.
2. wait()는 어떤 일이 일어나기를 기다릴 때 사용하는 메소드이다
3. notifyAll()는 어떤 일이 일어났을 때 이를 알려주는 메소드이다.
Exercise
1. CPU의 시간을 잘게 나누어서 스레드에게 각 슬라이스를 할당한다.
2.
(1) Thread클래스를 상속받아 서브 클래스를 만들고 run()메소드를 오버라이드하는 방법이다.
Thread클래스를 확장하는 방법은 자바에서는 단일 상속만이 가능하므로 다른 클래스를
이미 상속한 클래스는 스레드로 만들 수 없다.
(2) Runnable인터페이스는 스레드로 실행이 가능한 객체들이 만족하여야하는 인터페이스이
다. Runnable객체는 Thread가 아닌 다른 클래스를 상속 받을 수 있다.
3.
(1) 현재 스레드의 실행을 지정된 시간 동안 중단
(2) CPU를 다른 스레드에게 양보한다.
(3) run()을 호출하여 스레드를 실행시킨다.
4.
(1) 다음과 같은 출력을 내면서 무한 반복된다.
0
1
2
...
(2) class Job extends Thread ...
(3)
class Job extends Thread {
private String name;
public Job(String name) {
this.name = name;
}
public void run() {
byte n = 0;
while (true)
System.out.println(name + n++);
}
}
public class Test {
public static void main(String[] args) {
Job j = new Job("Thread1");
j.start();
}
}
(4) 두 개의 스레드가 번갈아 가면서 실행된다.
class Job extends Thread {
private String name;
public Job(String name) {
this.name = name;
}
public void run() {
byte n = 0;
while (true)
System.out.println(name + n++);
}
}
public class Test {
public static void main(String[] args) {
Job j1 = new Job("Thread1");
j1.start();
Job j2 = new Job("Thread2");
j2.start();
}
}
5.
A
C
D
Programming
1.
import
import
import
import
import
import
import
import
import
import
java.awt.BorderLayout;
java.awt.Color;
java.awt.Font;
java.awt.Graphics;
java.awt.GridLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.text.DecimalFormat;
import
import
import
import
import
javax.swing.JButton;
javax.swing.JComponent;
javax.swing.JFrame;
javax.swing.JPanel;
javax.swing.border.EmptyBorder;
public class SecondCounterDemo extends JPanel {
private SecondCounterRunnable sc = new SecondCounterRunnable();
private JButton startB = new JButton("카운터 시작");
private JButton stopB = new JButton("카운터 중지");
public SecondCounterDemo() {
stopB.setEnabled(false);
startB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
startB.setEnabled(false);
Thread counterThread = new Thread(sc, "Counter");
counterThread.start();
stopB.setEnabled(true);
stopB.requestFocus();
}
});
stopB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
stopB.setEnabled(false);
sc.stopClock();
startB.setEnabled(true);
startB.requestFocus();
}
});
JPanel innerButtonP = new JPanel();
innerButtonP.setLayout(new GridLayout(0, 1, 0, 3));
innerButtonP.add(startB);
innerButtonP.add(stopB);
JPanel buttonP = new JPanel();
buttonP.setLayout(new BorderLayout());
buttonP.add(innerButtonP, BorderLayout.NORTH);
this.setLayout(new BorderLayout(10, 10));
this.setBorder(new EmptyBorder(20, 20, 20, 20));
this.add(buttonP, BorderLayout.WEST);
this.add(sc, BorderLayout.CENTER);
}
public static void main(String[] args) {
SecondCounterDemo scm = new SecondCounterDemo();
JFrame f = new JFrame();
f.setContentPane(scm);
f.setSize(320, 200);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
class SecondCounterRunnable extends JComponent implements Runnable {
private volatile boolean keepRunning;
private Font paintFont = new Font("SansSerif", Font.BOLD, 14);
private volatile String timeMsg = "never started";
private volatile int arcLen = 0;
public SecondCounterRunnable() {
}
public void run() {
runClock();
}
public void runClock() {
DecimalFormat fmt = new DecimalFormat("0.000");
long normalSleepTime = 100;
int counter = 0;
keepRunning = true;
while (keepRunning) {
try {
Thread.sleep(normalSleepTime);
} catch (InterruptedException x) {
}
counter++;
double counterSecs = counter / 10.0;
timeMsg = fmt.format(counterSecs);
arcLen = (((int) counterSecs) % 60) * 360 / 60;
repaint();
}
}
public void stopClock() {
keepRunning = false;
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.setFont(paintFont);
g.drawString(timeMsg, 0, 15);
g.fillOval(0, 20, 100, 100);
g.setColor(Color.white);
g.fillOval(3, 23, 94, 94);
g.setColor(Color.red);
g.fillArc(2, 22, 96, 96, 90, -arcLen);
}
}
}
2. 생략
3.
import
import
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Dimension;
java.awt.FlowLayout;
java.awt.Font;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.RenderingHints;
java.awt.font.FontRenderContext;
java.awt.font.TextLayout;
java.awt.geom.Rectangle2D;
java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ScrollText extends JComponent {
private BufferedImage image;
private Dimension imageSize;
private volatile int currOffset;
private Thread internalThread;
private volatile boolean noStopRequested;
public ScrollText(String text) {
currOffset = 0;
buildImage(text);
setMinimumSize(imageSize);
setPreferredSize(imageSize);
setMaximumSize(imageSize);
setSize(imageSize);
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch (Exception x) {
x.printStackTrace();
}
}
};
internalThread = new Thread(r, "ScrollText");
internalThread.start();
}
private void buildImage(String text) {
RenderingHints renderHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
renderHints.put(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
BufferedImage scratchImage = new BufferedImage(1, 1,
BufferedImage.TYPE_INT_RGB);
Graphics2D scratchG2 = scratchImage.createGraphics();
scratchG2.setRenderingHints(renderHints);
Font font = new Font("Serif", Font.BOLD | Font.ITALIC, 24);
FontRenderContext frc = scratchG2.getFontRenderContext();
TextLayout tl = new TextLayout(text, font, frc);
Rectangle2D textBounds = tl.getBounds();
int textWidth = (int) Math.ceil(textBounds.getWidth());
int textHeight = (int) Math.ceil(textBounds.getHeight());
int horizontalPad = 10;
int verticalPad = 6;
imageSize = new Dimension(textWidth + horizontalPad, textHeight
+ verticalPad);
image = new BufferedImage(imageSize.width, imageSize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHints(renderHints);
int baselineOffset = (verticalPad / 2) - ((int) textBounds.getY());
g2.setColor(Color.white);
g2.fillRect(0, 0, imageSize.width, imageSize.height);
g2.setColor(Color.blue);
tl.draw(g2, 0, baselineOffset);
scratchG2.dispose();
scratchImage.flush();
g2.dispose();
}
public void paint(Graphics g) {
g.setClip(0, 0, imageSize.width, imageSize.height);
int localOffset = currOffset;
g.drawImage(image, -localOffset, 0, this);
g.drawImage(image, imageSize.width - localOffset, 0, this);
g.setColor(Color.black);
g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
}
private void runWork() {
while (noStopRequested) {
try {
Thread.sleep(100);
currOffset = (currOffset + 1) % imageSize.width;
repaint();
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
public static void main(String[] args) {
ScrollText st = new ScrollText("우리는 스레드로 애니메이션을 할 수 있어
요!");
JPanel p = new JPanel(new FlowLayout());
p.add(st);
JFrame f = new JFrame("ScrollText Demo");
f.setContentPane(p);
f.setSize(400, 100);
f.setVisible(true);
}
}
4.
import
import
import
import
import
import
import
import
import
import
import
java.awt.Color;
java.awt.Dimension;
java.awt.FlowLayout;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.Image;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.awt.geom.Ellipse2D;
java.awt.geom.Rectangle2D;
java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class SwingWithThread extends JComponent {
private Image[] frameList;
private long msPerFrame;
private volatile int currFrame;
private Thread internalThread;
private volatile boolean noStopRequested;
public SwingWithThread(int width, int height, long msPerCycle,
int framesPerSec, Color fgColor) {
setPreferredSize(new Dimension(width, height));
int framesPerCycle = (int) ((framesPerSec * msPerCycle) / 1000);
msPerFrame = 1000L / framesPerSec;
frameList = buildImages(width, height, fgColor, framesPerCycle);
currFrame = 0;
noStopRequested = true;
Runnable r = new Runnable() {
public void run() {
try {
runWork();
} catch (Exception x) {
// in case ANY exception slips through
x.printStackTrace();
}
}
};
internalThread = new Thread(r);
internalThread.start();
}
private Image[] buildImages(int width, int height, Color color, int count) {
BufferedImage[] im = new BufferedImage[count];
for (int i = 0; i < count; i++) {
im[i] = new BufferedImage(width, height,
BufferedImage.TYPE_INT_ARGB);
double xShape = ((double) (i * width)) / (double) count;
;
double yShape = ((double) (i * height)) / (double) count;
double wShape = 2.0 * (width - xShape);
double hShape = 2.0 * (height - yShape);
Rectangle2D shape = new Rectangle2D.Double(xShape, yShape,
wShape,
hShape);
Graphics2D g2 = im[i].createGraphics();
g2.setColor(color);
g2.fill(shape);
g2.dispose();
}
return im;
}
private void runWork() {
while (noStopRequested) {
currFrame = (currFrame + 1) % frameList.length;
repaint();
try {
Thread.sleep(msPerFrame);
} catch (InterruptedException x) {
Thread.currentThread().interrupt();
}
}
}
public void stopRequest() {
noStopRequested = false;
internalThread.interrupt();
}
public boolean isAlive() {
return internalThread.isAlive();
}
public void paint(Graphics g) {
g.drawImage(frameList[currFrame], 0, 0, this);
}
public static void main(String[] args) {
SwingWithThread redSquish = new SwingWithThread(250, 200, 2500L, 10,
Color.red);
JFrame f = new JFrame();
f.setLayout(new FlowLayout());
f.add(redSquish);
f.setSize(450, 250);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
Related documents