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
}
}

 

Method Overloading vs Overriding

http://www.programmerinterview.com/index.php/java-questions/method-overriding-vs-overloading/

Method Overloading: 동일한 함수명에 매개변수가 다른 함수를 둘 이상 정의하는 것으로, 동일한 함수 기능을 수행하지만 다른 매개변수의 경우를 처리할 때 사용
//compiler error – can’t overload based on the 
//type returned (one method returns int, the other returns a float):
//int changeDate(int Year) ;
//float changeDate (int Year);

//compiler error – can’t overload by changing just
//the name of the parameter (from Year to Month):
//int changeDate(int Year);
//int changeDate(int Month) ;

//valid case of overloading,
//since the methods have different number of parameters:
int changeDate(int Year, int Month) ;
int changeDate(int Year);

//also a valid case of overloading,
//since the parameters are of different types:
int changeDate(float Year) ;
int changeDate(int Year);

Method Overriding: 상속받은 파생 클래스에서 동일한 함수명에 동일한 매개변수로 정의하여 함수를 재정의하는 것으로 상속되어진 함수의 기능을 변경해서 재사용하고 싶을 때 사용

public class Parent {

public int someMethod() {

return 3;

}
}

public class Child extends Parent{

// this is method overriding:
public int someMethod() {

return 4;

}

}

protected constructor

protected constructor는 추상클래스 (abstract class)에서 사용을 권고함. 추상 클래스를 상속받는 파생클래스에서 파생 클래스 생성자가 부모 클래스 즉, 추상 클래스를 초기화 하기 위해 추상 클래스 생성자를 호출 할 수 있도록 지원함.
public abstract class Shape
{

protected Shape(String name) { this.name = name; }
private String name;
public void print() { System.out.print(this.name); }
}
public class Triangle extends Shape
{
private double bottom, height;

public Triangle(String name) { super(name); this.bottom = 1; this.height = 1; }

public void print()
{
super.print();
System.out.printf(” 밑변: %f 높이: %f\n”, this.bottom, this.height);
}
}
public class Rectangle extends Shape
{
private double width, height;

public Rectangle(String name) { super(name); this.width = 2; this.height = 3; }

public void print()
{
super.print();
System.out.printf(” 가로: %f 세로: %f\n”, this.width, this.height);
}
}
class ShapeTest
{
public static void main(String[] args)
{
// Shape s = new Shape(“도형”); // Error; Shape is abstract; cannot be instantiated
Shape s = new Triangle(“삼각형”);
s.print(); // 삼각형 밑변: 1 높이: 1
s = new Rectangle(“직사각형”);
s.print(); // 직사각형 가로: 2 세로: 3
}
}

 

private constructor

private constructor는 정적 메소드와 속성 (static method & property)만 있는 경우 사용함.

public class Counter
{
private Counter() { }
public static int currentCount;
public static int IncrementCount() { return ++currentCount; }
}
class TestCounter
{
public static void main(String[] args)
{
// If you uncomment the following statement, it will generate
// an error because the constructor is inaccessible:
// Counter aCounter = new Counter(); // Error
Counter.currentCount = 100;
Counter.IncrementCount();
System.out.println(“count=” + Counter.currentCount);
}

} // Output: New count: 101

HW2

단국대학교 응용컴퓨터공학전공 JAVA프로그래밍1 (2016년 가을학기) 실습
과목코드 : 514760-1
날짜: 2016년 10월 6일

– 실습번호 : HW2 (Due by 10/20)
– 실습제목 : class, abstract class, inheritance, set/get, ArrayList
– 실습요약 : 입체 도형의 겉넓이(surface area)와 부피(volume) 구하기 & 평면 도형의 넓이(area) 구하기
– 준비자료 : HW1
http://www.mathsisfun.com/area-calculation-tool.html
http://math.about.com/od/formulas/ss/surfaceareavol.htm

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

– 실습문제
0. GeometryType과 FigureType을 아래와 같이 정의한다.
enum GeometryType { SPHERE(1), CONE(2), CYLINDER(3), RECTANGULAR_PRISM(4), SQUARE_PYRAMID(5), ISOSCELES_TRIANGULAR_PRISM(6) }
enum FigureType { TRIANGLE(1), SQUARE(2), RECTANGLE(3), PARALLELOGRAM(4), RHOMBUS(5), TRAPEZOID(6) }

1. Geometry와 Figure 추상클래스는 아래와 같이 정의한다.
public abstract class Geometry {
public abstract GeometryType getType(); // 도형타입 (GeometryType)
public abstract double getSurfaceArea(); // 겉넓이
public abstract double getVolume(); // 부피
public abstract void getAdditionalUserInput(); // 추가적인 사용자 입력
public void printInfo() {
System.out.println(toString() + “ S.A.=” + getSurfaceArea() + “ Vol=” + getVolume());
}
public abstract class Figure {
public abstract FigureType getType(); // 도형타입 (FigureType)
public abstract double getArea(); // 넓이
public abstract void getAdditionalUserInput(); // 추가적인 사용자 입력
public void printInfo() {
System.out.println(toString() + “Area=” + getArea());
}

2. Geometry 추상클래스를 상속받은 Sphere, Cone, Cylinder, … 는 겉넓이(Surface Area), 부피(Volume)를 계산하여 출력한다. 그리고 Figure 추상클래스를 상속받은 Triangle, Square, Rectangle, … 등 클래스는 넓이(Area)를 계산하여 출력한다.

3. GeometryFactory 클래스와 FigureFactory 클래스는 사용자가 입력한 도형타입에 따라 원하는 실제 클래스 (즉, Sphere, Cone, … 그리고 Triangle, Square,.. 등등) 객체를 생성하여 계산한다. 이 클래스는 다음의 메소드 (Method)만을 갖는다.
+public static Geometry getInstance(GeometryType type)
+public static Figure getInstance(FigureType type)

4. GeometryCalculator 클래스와 FigureCalculator 클래스는 계산 메소드를 갖는다
+ public static void calculateAll() // ArrayList에 Geometry/Figure 객체를 생성하여 넣고, 각각의 SurfaceArea&Volume/Area계산한다.
+ public static void calculateByUserInput() // 사용자 입력으로 원하는 Geometry /Figure객체를 생성하여 SurfaceArea&Volume/Area를 계산하고, ArrayList에 저장해 두었다가 프로그램을 종료할 시 전체 리스트를 출력한다.

5. Utility 클래스에서는 각종 유틸리티 메소드를 갖는다.
+public static GeometryType getUserGeometry()
+public static FigureType getUserFigure()
+public static double getUserInputDouble()
+public static int getUserInputBetween(int min, int max)
+public static boolean getUserExitKey()

6. GeoFigCalculator 클래스에서는 사용자의 입력에 따라 GeometryCalculator와 FigureCalculator를 이용하여 계산한 모든 결과를 출력한다.

7. 사용자의 잘못된 입력에 따른 처리를 반드시 포함해야 하며, 그 외에 본인이 더 테스트해보고 싶은 method나 routine을 추가하라. 실행 화면과 코드를 첨부하시오.