GeometryType

import java.util.*;

public enum GeometryType {
NONE(0),
SPHERE(1),
CONE(2),
CYLINDER(3),
RECTANGULAR_PRISM(4),
SQUARE_PYRAMID(5),
ISOSCELES_TRIANGULAR_PRISM(6);

private int type;

private GeometryType(int type) {
this.type = type;
}

public int getType() {
return type;
}

public static GeometryType valueOf(int value) {
switch(value) {
case 1:
return SPHERE;
case 2:
return CONE;
case 3:
return CYLINDER;
case 4:
return RECTANGULAR_PRISM;
case 5:
return SQUARE_PYRAMID;
case 6:
return ISOSCELES_TRIANGULAR_PRISM;
default:
return null;
}
}

public static GeometryType nameOf(String name) {
if (name.contentEquals(“SPHERE”) || name.contentEquals(“Sphere”))
return SPHERE;
else if (name.contentEquals(“CONE”) || name.contentEquals(“Cone”))
return CONE;
else if (name.contentEquals(“CYLINDER”) || name.contentEquals(“Cylinder”))
return CYLINDER;
else if (name.contentEquals(“RECTANGULAR_PRISM”) || name.contentEquals(“RectangularPrism”))
return RECTANGULAR_PRISM;
else if (name.contentEquals(“SQUARE_PYRAMID”) || name.contentEquals(“SquarePyramid”))
return SQUARE_PYRAMID;
else if (name.contentEquals(“ISOSCELES_TRIANGULAR_PRISM”) || name.contentEquals(“IsoscelesTriangularPrism”))
return ISOSCELES_TRIANGULAR_PRISM;
else
return null;
}

public static String[] names() {
String[] names = new String[GeometryType.values().length];
for (GeometryType t : GeometryType.values())
names[t.ordinal()] = t.toString();
return names;
}
}

Midterm Extra 20%

Midterm Extra 20% (due by 11/16 23:59)

-중간고사 시험문제 프로그램(Point, Point3D, Bound, PolygonType, RegularPolygon, Utility)을 똑같이 작성하고 실행결과를 확인한다.

-이 프로그램을 직접 실행시켜서 중간고사 본인 답안과 비교 분석하는 보고서를 작성한다. (장수제한없음)

-중간고사 시험문제를 다시 푼다. (장수제한없음)

 

public class Point {
// 중간생략..
    public double[] get()
{
double[] xy = new double[2];
xy[0] = this.x;
xy[1] = this.y;
System.out.println(“get(): ” + “(” + xy[0] + “, ” + xy[1] + “)”);
return xy;
}
    public void set(double[] xy)
{
if (xy.length == 2) {
this.x = xy[0];
this.y = xy[1];
System.out.println(“set(xy[]): ” + this);
}
}
}
public class ArrayTest {
 public static void swap2(Point p, Point q)        // Java uses pass-by-value
{
  double[] t = p.get(); // T t = p
p.set(q.get());  // p = q
q.set(t);  // q = t
}
}

HW3

단국대학교 응용컴퓨터공학전공 JAVA프로그래밍1 (2016년 가을학기) 실습

날짜: 2016년 11월 10일

 

– 실습번호 : lab-03 (Due by 11/24)

– 실습제목 : GUI, swing, event

– 실습요약 : GUI 기반 입체 도형의 겉넓이(surface area)와 부피(volume) 구하기

– 준비자료 : HW2

 

11/24까지 online.dankook.ac.kr 이러닝으로 source code(*.java), binary code(*.class), 보고서(12-font 2~3 page)를 학번_이름_Ex3.zip으로 묶어서 이러닝에 제출한다. 보고서 (30%)

 

– 실습문제

  1. IGeometry 인터페이스와 Geometry 추상클래스는 아래와 같이 정의한다.

public interface IGeometry {

double getSurfaceArea(); // 겉넓이

double getVolume(); // 부피

}

public abstract class Geometry implements IGeometry {

public abstract GeometryType getType(); // 도형타입 (GeometryType)

}

 

  1. Geometry 추상클래스를 상속받은 Sphere, Cone, Cylinder, … 는 겉넓이(Surface Area), 부피(Volume)를 계산하여 출력한다.

 

  1. JFrame와 ItemListener와 KeyListener를 상속받은 GeometryFrame 클래스는 GUI를 정의하고 Geometry 계산을 구현한다.

-JComboBox, JLabel, JTextField, JButton, JPanel을 사용하여 GUI를 정의한다.

-Geometry 객체를 생성해서 텍스트필드에서 입력받은 값으로 SurfaceArea와 Volume을 계산하여 화면에 출력한다.

-public void itemStateChanged(ItemEvent e) { // 콤보박스 이벤트 내부구현 요망 }

-public void keyPressed(KeyEvent e) { // 키이벤트 관련 메소드 구현 요망 }

HW2 Utility.java

import java.util.Scanner;

public class Utility {
// get user input double
public static double getUserInputDouble() {
double value;
Scanner scan = new Scanner(System.in);
while(true) {
try {
value = scan.nextDouble();
break;
}
catch (Exception e) {
System.out.print(“Error! Please re-enter [double value]: “);
scan.next();
}
}
return value;
}

// get between min_value and max_value
public static int getUserInputBetween(int min, int max)
{
int value = 0;
Scanner scan = new Scanner(System.in);
do {
System.out.printf(“Please enter the value %d-%d.\n”, min, max);
try {
value = scan.nextInt();
} catch (Exception e) {
System.out.printf(“ERROR! Valid range %d-%d. Please re-enter!\n”, min, max);
scan.next();
continue;
}
} while (value < min || value > max);
return value;
}

// get user input ‘q’-key
public static boolean getUserExitKey()
{
System.out.println(“Press q-key to exit the program or enter-key to start the program”);
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();
if (s.contentEquals(“q”)) {
return true;
}
else {
return false;
}
}

public static FigureType getUserFigure()
{
FigureType type = null;
Scanner scan = new Scanner(System.in);
do {
System.out.println(“Please select Figure [TRIANGLE, SQUARE, RECTANGLE, PARALLELOGRAM, RHOMBUS, TRAPEZOID]”);
try {
String inputString = scan.nextLine();
type = FigureType.nameOf(inputString);
if (type != null) return type;
} catch (Exception e) {
System.out.println(“ERROR! Please re-enter!”);
scan.next();
}
} while (type == null);
return type;
}

public static GeometryType getUserGeometry()
{
GeometryType type = null;
Scanner scan = new Scanner(System.in);
do {
System.out.println(“Please select geometry [SPHERE, CONE, CYLINDER, RECTANGULAR_PRISM, SQUARE_PYRAMID, ISOSCELES_TRIANGULAR_PRISM]:”);
try {
String inputString = scan.nextLine();
type = GeometryType.nameOf(inputString);
if (type != null) return type;
} catch (Exception e) {
System.out.println(“ERROR! Please re-enter!”);
scan.next();
}
} while (type == null);
return type;
}
}

Person & Student Class

// Person

class Person
{
private static int count = 0; // static (class) variables
protected String name; // instance variables
protected int age; // instance variables
public Person() { // default constructor
this(“”, 0);
}
public Person(String name, int age) {
count++;
this.name = name;
this.age = 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;
}
public void set(String name, int age){
this.name = name;
this.age = age;
}
public void set(Person other){
this.set(other.name, other.age);
}
public Person clone(){
return new Person(this.name, this.age);
}
public String toString() { // Object.toString() overriding
return “Person Name: ” + name + ” Age: ” + age;
}
public void print() { // instance method & virtual method
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}
public static void printCount(){ // static (class) methods
System.out.println(“Person Count: ” + count);
}
public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods
}

// Student

class Student extends Person
{
private static int count = 0; // static (class) variables
protected int id;
public Student() {
id = 5208;
}
public Student(String name, int age, int id) {
super(name, age);
this.id = id;
count++;
}
public int getID() {
return id;
}
public void setID(int id) {
this.id = id;
}
public void set(String name, int age, int id){
super.set(name, age);
this.id = id;
}
public void set(String name, int age){
super.set(name, age);
}
public void set(Student other){
this.set(other.name, other.age, other.id);
}
public void set(Person other){
if (other instanceof Student)
this.set((Student)other);
else
super.set(other);
}
public Student clone(){
return new Student(this.name, this.age, this.id);
}
public String toString() { // Object.toString() overriding
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}
public void print() { // Person class print() method overriding
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}
public void superPrint() {
super.print();
}
public static void printCount() { // static (class) methods
System.out.println(“Student Count: ” + count);
}
public static int getCount() { return count; } // static (class) methods
public static void setCount(int value) { count = value; } // static (class) methods
}

// PersonStudentTest

class PersonStudentTest
{
static void print(Object o) {
System.out.println(o);
}
static void print(Person[] arr) {
for (Person p : arr)
System.out.println(p);
}
public static void main(String[] args)
{
Person h1 = new Person(“JAVA”, 2016);
h1.print();
print(h1);
System.out.println(h1);

Person h2 = new Student(); // 기본생성자를 불렀을때 자기 count를 증가시키지 않는다
//h2.print();
// print(h2);
//System.out.println(h2);

Object o = h2; // upcasting
print(o); // dynamic binding
((Student)o).print();
((Person)o).print(); // o=> Person type => Person.print() => dynamic binding Student.print()

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();
}
}

// PersonStudentTest

class PersonStudentTest
{
static void print(Object o) {
System.out.println(o);
}
static void print(Person[] arr) {
for (Person p : arr)
System.out.println(p);
}
public static void main(String[] args)
{
Person h1 = new Person(“JAVA”, 2016);
h1.print();
print(h1);
System.out.println(h1);

Person h2 = new Student(); // 기본생성자를 불렀을때 자기 count를 증가시키지 않는다
//h2.print();
// print(h2);
//System.out.println(h2);

Object o = h2; // upcasting
print(o); // dynamic binding
((Student)o).print();
((Person)o).print(); // o=> Person type => Person.print() => dynamic binding Student.print()

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();

Person[] pList = new Person[5];
pList[0] = new Person(“JAVA1”, 1);
pList[0].print();
pList[1] = pList[0];
pList[1].print();
pList[2] = new Student(); // default constructor count증가 안함
pList[2].print();
pList[3] = new Student(“JAVA2”, 2, 222); // Student.count++
pList[3].print();
pList[4] = pList[3];
pList[4].print();

System.out.println(“AFTER SET”);
pList[0].set(“JAVA3”, 3); // Person.set(string, int)
pList[4].set(“JAVA4”, 4); // Person.set(string, int)
print(pList);

System.out.println(“AFTER SET2”);
Student s = (Student)pList[4]; // down casting
s.set(“JAVA5”, 5, 555); // Student.set(string, int, int)
print(pList);

System.out.println(“AFTER SET3”);
pList[0].set(pList[4]); // Person.set(Person)
print(pList);

System.out.println(“AFTER SET4”);
((Student)pList[2]).set(pList[4]); // Student.set(Person)
//((Student)pList[2]).set((Student)pList[4]); // Student.set(Student)
print(pList);

System.out.println(“AFTER SET5”);
((Student)pList[2]).set(new Person(“JAVA6”, 6)); // Student.set(Person)
//((Student)pList[2]).set((Student)pList[4]); // Student.set(Student)
print(pList);

Person.printCount(); // calls Person printCount()
Student.printCount(); // calls Student printCount()
System.out.println();
}
}

 

Java swap pass-by-value

static void swap(int p, int q) // Java uses pass-by-value
{
int t = p;
p = q;
q = t;
}

static void swap2(int[] p, int[] q)  // Java uses pass-by-value
{
int t = p[0];
p[0] = q[0];
q[0] = t;
}

static void swap(int[] p, int[] q)  // Java uses pass-by-value
{
int[] t = p;
p = q;
q = t;
}

static void swap2(int[][] p, int[][] q)  // Java uses pass-by-value
{
int[] t = p[0];
p[0] = q[0];
q[0] = t;
}

static void swap(Point p, Point q)        // Java uses pass-by-value
{
Point t = p;
p = q;
q = t;
}

static void swap2(Point p, Point q)        // Java uses pass-by-value
{
double[] t = p.get(); // T t = p
p.set(q.get());  // p = q
q.set(t);  // q = t
}

////////////////////////////////////////

public static void main(String[] args)
{
Point p1 = new Point(10.5, 10.7);
Point p2 = new Point(1.5, 1.7);

swap(p1, p2);
System.out.println(“After swap p1=” + p1 + ” p2 ” + p2); // p1=(10.5, 10.7) p2=(1.5, 1.7)
swap2(p1, p2);
System.out.println(“After swap2 p1=” + p1 + ” p2 ” + p2); // p1=(1.5, 1.7) p2=(10.5, 10.7)

int[] arr1 = { 1, 2, 3 };
int[] arr2 = { 4, 5, 6, 7, 8 };
swap(arr1, arr2);
System.out.print(“arr1: “);
System.out.println(Arrays.toString(arr1)); // arr1: [1, 2, 3]
System.out.print(“arr2: “);
System.out.println(Arrays.toString(arr2)); // arr2: [4, 5, 6, 7, 8]

int[][] array1 = { new int[] { 1, 2, 3 } };
int[][] array2 = { new int[] { 4, 5, 6, 7, 8 } };
swap2(array1, array2);
System.out.print(“array1: “);
System.out.println(Arrays.toString(array1[0])); // array1: [4, 5, 6, 7, 8]
System.out.print(“array2: “);
System.out.println(Arrays.toString(array2[0])); // array2: [1, 2, 3]

int a = 10;
int b = 20;
swap(a, b);
System.out.println(“a=” + a); // a=10
System.out.println(“b=” + b); // b=20

int[] a2 = { 10 };
int[] b2 = { 20 };
swap2(a2, b2);
System.out.println(“a2=” + a2[0]); // a2 = 20
System.out.println(“b2=” + b2[0]); // b2 = 10
}

 

Instance vs Static Method Overriding

PersonStudentClass

/// Person

class Person
{
static int count = 0; // static (class) variables

String name; // instance variables
int age; // instance variables

public Person()
{
//System.out.println(“Person Constructor”); // this(“”, 0); error: call to this must be first statemenht in constructor
this(“”, 0);
}

public Person(String name, int age)
{
count++;
this.name = name;
this.age = age;
}

public static void printCount() // static (class) method
{
System.out.println(“Person Count: ” + count);
}

public static int getCount() { return count; } // static (class) methods

 

public String toString() // Object.toString() overriding
{
return “Person Name: ” + name + ” Age: ” + age;
}

public void print() // instance methods
{
System.out.println(“Person Name: ” + name + ” Age: ” + age);
}
}

/// Student

class Student extends Person
{
static int scount = 0; // static (class) variables
int id;

public Student()
{
this(“”, 0, 5208);
}

public Student(String name, int age, int id)
{
super(name, age);
this.id = id;
scount++;
}

public static void printCount() // static (class) method overriding
{
System.out.println(“Student Count: ” + scount);
}

public String toString() // Object.toString() overriding
{
return “Student Name: ” + name + ” Age: ” + age + ” ID: ” + id;
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” ID: ” + id);
}

}

 

class PersonStudentTest
{
public static void main(String[] args)
{
Person p1 = new Student(“Kyoung”, 22, 1207);
p1.print(); // dynamic binding Student Name: Kyoung Age: 22 ID: 1207
p1.name = “JAVA”; // default (package private)
p1.age = 1; // default (package private)
//p1.id = 2016; // default (package private) cannnot call id coz Person System.out.println(p1); // dynamic binding Student Name: JAVA Age: 1 ID: 1207
p1.printCount(); // calls Person p1 printCount() 1
Person.printCount(); // calls Person printCount() 1
Student.printCount(); // calls Student printCount() 1
System.out.println();

Student s1 = (Student)p1;
s1.name = “JAVA”; // default (package private)
s1.age = 2; // default (package private)
s1.id = 2016; // default (package private)
s1.print(); // Student Name: JAVA Age: 2 ID: 2016
s1.printCount(); // calls Student s1 printCount() 1
Person.printCount(); // calls Person printCount() 1
Student.printCount(); // calls Student printCount() 1
System.out.println();

Student s2 = new Student(“Shin”, 20, 1207);
s2.print(); // Student Name: Shin Age: 20 ID: 1217
s2.printCount(); // calls Student s2 printCount() 2
Person.printCount(); // calls Person printCount() 2
Student.printCount(); // calls Student printCount() 2
System.out.println();

Person p2 = new Person(“Park”, 10);
p2.printCount(); // calls Person p2 printCount() 3
Person.printCount(); // calls Person printCount() 3
Student.printCount(); // calls Student printCount() 2
System.out.println();

Person p3 = new Person();
p3.printCount(); // calls Person p3 printCount() 4
Person.printCount(); // calls Person printCount() 4
Student.printCount(); // calls Student printCount() 2
System.out.println();

System.out.println(“Number of Person: ” + Person.getCount()); // 4
}
}