## PointLib & ShapeDrawing

1. create a package (PointLib)

1.1 Point 클래스를 추가한다.
PointLib

2. create a package (ShapeApp)

ShapeApp

2.1. RandomShape 클래스를 추가한다.

package ShapeApp;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

public class RandomShape {
Shape shape;
Color color;

RandomShape(Shape s, Color c) {
shape = s;
color = c;
}

public Shape getShape() {
return shape;
}

public void draw(Graphics2D g) {
g.setColor(color);
g.fill(shape);
}

boolean contains(int x, int y) {
return shape.contains((double) x, (double) y);
}

void translate(int x, int y) {
if (shape instanceof Polygon) {
Polygon p = (Polygon) shape;
p.translate(x, y);
}
else if (shape instanceof Rectangle) {
Rectangle r = (Rectangle) shape;
r.translate(x, y);
}
else if (shape instanceof Ellipse2D) {
Ellipse2D e = (Ellipse2D) shape;
e.setFrame((double) x, (double) y, e.getWidth(), e.getHeight());
}
}
}

2.2. RandomShapeFactory 클래스를 추가한다.

package ShapeApp;

import java.awt.Color;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.util.Random;

import PointLib.Point;

public class RandomShapeFactory {

private static Random rand = new Random();

public static Color randomColor() {
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
return new Color(r, g, b);
}

public static int randomInt(int min, int max) {
return rand.nextInt(max-min) + min;
}

public static RandomShape getInstance(Point center) {
int shapeType = rand.nextInt() % 3;
System.out.println(“ShapeType=” + shapeType);
switch (shapeType) {
case 1:
{
System.out.println(“Triangle”);
int size = randomInt(20, 30);
Polygon triangle = new Polygon();
RandomShape s = new RandomShape(triangle, randomColor());
return s;
}

case 2:
{
System.out.println(“Rectangle”);
Shape rectangle = new Rectangle((int) center.getX(), (int) center.getY(), randomInt(50, 60), randomInt(50, 60));
RandomShape s= new RandomShape(rectangle, randomColor());
return s;
}

default:
{
System.out.println(“Oval”);
Shape oval = new Ellipse2D.Double(center.getX(), center.getY(), randomInt(40, 50), randomInt(30, 40));
RandomShape s= new RandomShape(oval, randomColor());
return s;
}
}
}
}

2.3. ShapeDrawing 클래스를 추가한다.

package ShapeApp;

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.util.*;
import java.awt.event.*;

import PointLib.Point;

// ShapeDrawing
public class ShapeDrawing extends JFrame {
ShapeDrawingPanel polyCanvas = new ShapeDrawingPanel();

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

public ShapeDrawing() {
super(“Shape Drawing Frame”);

setBounds(10, 10, 350, 350);
setResizable(false);
setVisible(true);

polyCanvas.setPreferredSize(new Dimension(300, 300));

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

private class ShapeDrawingPanel extends JPanel implements MouseListener, MouseMotionListener
{
int lastX, lastY;
boolean dragging = false;

ArrayList<RandomShape> shapes = new ArrayList<RandomShape>();
RandomShape selectedShape = null;

public ShapeDrawingPanel()
{
System.out.println(“ShapeDrawingPanel”);
}

@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

for (RandomShape s : shapes)
s.draw(g2);
}

RandomShape findShape(int x, int y)
{
RandomShape s = null;
for (int i = shapes.size() – 1; i >= 0; i–) {
s = (RandomShape) shapes.get(i);
if (s.contains(x, y)) {
System.out.println(“Selected”);
return s;
}
}
return null;
}

public void mouseDragged(MouseEvent e) {
if (dragging == true) {
if (selectedShape.getShape() instanceof Ellipse2D)
selectedShape.translate(e.getX(), e.getY());
else {
int deltaX = e.getX() – lastX;
int deltaY = e.getY() – lastY;
System.out.println(“x = ” + deltaX + ” y = ” + deltaY);
selectedShape.translate(deltaX, deltaY);
lastX = e.getX();
lastY = e.getY();
}
repaint();
}
}

public void mouseMoved(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {
}

public void mousePressed(MouseEvent e) {
selectedShape = findShape(e.getX(), e.getY());
if (selectedShape != null) {
dragging = true;
lastX = e.getX();
lastY = e.getY();
}
else {
System.out.println(“Pressed”);
RandomShape s = RandomShapeFactory.getInstance(new Point((double) e.getX(), (double) e.getY()));
repaint(); // calls paintComponent()
}
}

public void mouseReleased(MouseEvent e) {
if (dragging == true) {
dragging = false;
selectedShape = null;
}
}

public void mouseEntered(MouseEvent e) {
}

public void mouseExited(MouseEvent e) {
}
}
}

## ShapeMaker

import java.awt.*;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.*;

public class ShapeMaker extends JFrame {

public static void main(String[] args) {
// TODO Auto-generated method stub
new ShapeMaker();
}

public ShapeMaker()
{
setSize(300, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

private class ShapeComponent extends JComponent {
ArrayList<Shape> shapes = new ArrayList<Shape>();

public ShapeComponent() {
Shape s = new Rectangle2D.Float(10, 10, 60, 80);

s = new RoundRectangle2D.Float(110, 10, 80, 80, 10, 10);

s = new Ellipse2D.Float(10, 110, 80, 80);

s = new Arc2D.Float(10, 210, 80, 80, 90, 90, Arc2D.OPEN);

s = new Arc2D.Float(110, 210, 80, 80, 0, 180, Arc2D.CHORD);

s = new Arc2D.Float(210, 210, 80, 80, 45, 90, Arc2D.PIE);
}

public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(Color.LIGHT_GRAY);
for (int i = 0; i < getSize().width; i += 10) {
g2.draw(new Line2D.Float(i, 0, i, getSize().height));
}
for (int i = 0; i < getSize().height; i += 10) {
g2.draw(new Line2D.Float(0, i, getSize().width, i));
}
g2.setColor(Color.BLACK);
for (Shape s : shapes) {
g2.draw(s);
}
}
}
}

## KoreaMapViewer

2. Set CLASSPATH (in system environment variables) ./;C:\JMapViewer-2.0\JMapViewer.jar;C:\JMapViewer-2.0\JMapViewer_src.jar;C:\JMapViewer-2.0\JMapViewer_Demo.jar

& compile Demo.java (src)

3. or, create a Java Project (KoreaMapViewer) in Eclipse

& create a new folder (lib) & add *.jar

& Configure Build Path & Add JARs

& compile Demo.java (src)

## HW4

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

– 실습번호 : lab-04 (Due by 12/15)
– 실습제목 : collections, fileIO, package
– 실습요약 : 지진데이터 뷰어
– 준비자료 : 지진데이터 data

JSOM (OpenStreeMap for Java8)
http://svn.openstreetmap.org/applications/viewer/jmapviewer/releases/2.0/JMapViewer-2.0.zip
JMapViewer-2.0

– 실습문제
1. KoreanQuake 클래스를 작성한다.

KEarthquake

2. KoreanQuakeManager 클래스는 지진데이터의 CSV 파일 입출력을 담당한다.
+ public static ArrayList loadCSV(String filename);
+ public static void writeCSV(String path, ArrayList qList);
+ CSV 파일 입출력 (지진 데이터를 quakeList에 import & quakeList를 새로운 파일로 export)
+ 주의: file 존재여부 및 위도/경도 정보가 없는 경우의 예외처리 요망https://www.tutorialspoint.com/java/java_exceptions.htm

3. KoreanQuakeMapViewer 클래스는 JMapViewer(https://josm.openstreetmap.de/)을 사용하여 KoreanQuake 데이터를 지도에 그려준다. http://dis.dankook.ac.kr/lectures/java16/2016/12/01/koreamapviewer/

map().addMapMarker(new MapMarkerCircle( /* 내용 지정 요망 */ )); // 아래 JOSM MapMarkerCircle을 참고하여 내용 지정 요망

https://josm.openstreetmap.de/doc/org/openstreetmap/gui/jmapviewer/MapMarkerCircle.html

4. KoreanQuakeTableFrame 클래스는 JTable를 사용하여 KoreanQuake 데이터를 테이블로 보여준다.

+JTable 사용법 http://www.java2s.com/Code/Java/Swing-JFC/CreatingaJTableComponent.htm
+ KoreanQuakeTableModel 클래스 정의 필요http://www.java2s.com/Code/Java/Swing-JFC/extendsAbstractTableModeltocreatecustommodel.htm

5. 본인이 더 테스트해보고 싶은 Method를 추가하라. 예를 들어, 디렉토리에 여러 개의 데이터를 읽어서, 여러 가지 방법으로 정렬 및 LINQ 쿼리를 한 후 새로운 파일에 저장한다. 등등. 실행 화면과 코드를 첨부하시오.

## EventHandler

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Button1Listener implements ActionListener { // (1) 독립적 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
button.setText(“버튼 1이 눌려졌습니다”);
}

}

class MyFrame extends JFrame implements ActionListener { // (3) 인터페이스 구현
JButton b1;
JButton b2;
JButton b3;
JButton b4;
JButton b5;

private class Button2Listener implements ActionListener { // (2) 내부 이벤트 클래스

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b2) {
b1.setText(“버튼2 이 눌려졌습니다”);
b2.setText(“버튼2 이 눌려졌습니다”);
b3.setText(“버튼2 이 눌려졌습니다”);
}
}

}

public MyFrame() {
setTitle(“Absolute Position Test”);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);

JPanel p = new JPanel();
p.setLayout(null); // 절대위치크기 지정
b1 = new JButton(“Button #1”);
b2 = new JButton(“Button #2”);
b3 = new JButton(“Button #3”);
b4 = new JButton(“Button #4”);
b5 = new JButton(“Button #5”);
b1.setBounds(20, 5, 95, 30); // 절대위치크기 지정
b2.setBounds(55, 45, 105, 70); // 절대위치크기 지정
b3.setBounds(180, 15, 105, 90); // 절대위치크기 지정
b4.setBounds(80, 120, 105, 40); // 절대위치크기 지정
b5.setBounds(20, 170, 200, 30); // 절대위치크기 지정

b1.addActionListener(new Button1Listener()); // (1) 독립적 이벤트 클래스 사용
b2.addActionListener(new Button2Listener()); // (2) 내부 이벤트 클래스 사용
b4.addActionListener(new ActionListener() { // (4) 무명 이벤트 클래스 사용
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == b4) {
b1.setText(“버튼4 이 눌려졌습니다”);
b2.setText(“버튼4 이 눌려졌습니다”);
b3.setText(“버튼4 이 눌려졌습니다”);
b4.setText(“버튼4 이 눌려졌습니다”);
}
}
});
b5.addActionListener(e -> { // (5) lambda 사용
b1.setText(“버튼5 이 눌려졌습니다”);
b2.setText(“버튼5 이 눌려졌습니다”);
b3.setText(“버튼5 이 눌려졌습니다”);
b4.setText(“버튼5 이 눌려졌습니다”);
b5.setText(“버튼5 이 눌려졌습니다”);
});

setVisible(true);
}

public void actionPerformed(ActionEvent e) { // (3) 인터페이스 구현

JButton button = (JButton) e.getSource();
if (button == b3) {
b1.setText(“버튼3 이 눌려졌습니다”);
b2.setText(“버튼3 이 눌려졌습니다”);
b3.setText(“버튼3 이 눌려졌습니다”);
}

}

}

public class AbsolutePositionTest {
public static void main(String args[]) {
MyFrame f = new MyFrame();
}
}

## Equals & Contains

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected 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 Person(Person other)
{
this(other.name, other.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 boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
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);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

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

public int compareTo(Person other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Person)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {

public int compare(Person p1, Person p2) {

int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

}

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

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

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

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

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” 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 Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

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

public int compareTo(Student other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Student)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Student> AgeComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

public static Comparator<Student> IDComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int id1 = p1.getID();
int id2 = p2.getID();

//ascending order
return id1 – id2;

//descending order
//return id2 – id1;
}

};
}

class PersonStudentTest
{

public static void main(String[] args)
{

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

Person jason1 = new Person(“Jason”, 10);
Person jason2 = new Person(“Jason”, 10);
Person jason3 = jason1;
Person jason4 = new Person(“Jason”, 20);

if (jason1 == jason2)
System.out.println(“jason1 == jason2”);
else
System.out.println(“jason1 != jason2”); //동일한 reference를 가리키지 않으므로 jason1 != jason2
if (jason1 == jason3)
System.out.println(“jason1 == jason3”); // 동일한 reference이므로 jason1 == jason3
else
System.out.println(“jason1 != jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 == jason4”);
else
System.out.println(“jason1 != jason4”); //동일한 reference를 가리키지 않으므로 jason1 != jason4

if (jason1.equals(jason2))
System.out.println(“jason1 equals to jason2”); // 내용이 같으므로  jason1 equals to jason2
else
System.out.println(“jason1 is not equal to jason2”);
if (jason1.equals(jason3))
System.out.println(“jason1 equals to jason3”); // 내용이 같으므로  jason1 equals to jason3
else
System.out.println(“jason1 is not equal to jason3”);
if (jason1.equals(jason4))
System.out.println(“jason1 equals jason4”);
else
System.out.println(“jason1 is not equal to jason4”); // 내용이 다르므로 jason1 is not equal to jason4

///////////////////////////////////////////////////////////////////////
Student john1 = new Student(“John”, 10, 100);
Student john2 = new Student(“John”, 10, 100);
Student john3 = john1;
Student john4 = new Student(“John”, 20, 100);
if (john1.equals(john2))
System.out.println(“john1 equals to john2”); // 내용이 같으므로  john1 equals to john2
else
System.out.println(“john1 is not equal to john2”);

if (john1.equals(john3))
System.out.println(“john1 equals to john3”); // 내용이 같으므로 jogn1 equals to john3
else
System.out.println(“john1 is not equal to john3”);

if (john1.equals(john4))
System.out.println(“john1 equals to john4”);
else
System.out.println(“john1 is not equal to john4”); // 내용이 다르므로 john1 is not equal to john4

Set<Student> sList5 = new HashSet<Student>();
sList5.forEach((s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

Hashtable<Integer, Student> sList6 = new Hashtable<Integer, Student>();
sList6.put(1, john1);
sList6.put(2, john2);
sList6.put(3, john3);
sList6.put(4, john4);
sList6.forEach((i, s) -> System.out.println(s));
System.out.println(“sList5 contains john1 Student(\”John\”, 10, 100): ” + sList5.contains(john1));
System.out.println(“sList5 contains john2 Student(\”John\”, 10, 100): ” + sList5.contains(john2));
System.out.println(“sList5 contains john3 Student(\”John\”, 10, 100): ” + sList5.contains(john3));
System.out.println(“sList5 contains john4 Student(\”John\”, 20, 100):: ” + sList5.contains(john4));
System.out.println(“sList5 contains Student(\”John\”, 20, 100): ” + sList5.contains(new Student(“John”, 20, 100)));
System.out.println(“sList5 contains Student(\”John\”, 20, 200): ” + sList5.contains(new Student(“John”, 20, 200)));

}

}

## Comparable & Comparator Interface

PersonStudentInterface

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

import java.util.*;

class Person implements Comparable<Person>
{
private static int count = 0;   // static (class) variables

protected String name;    // instance variables
protected 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 Person(Person other)
{
this(other.name, other.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 boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Person) {
Person that = (Person) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge();
}
return false;
}

@Override
public int hashCode() {
return (41 * getName().hashCode() + getAge());
}

public boolean canEqual(Object other) {
return (other instanceof Person);
}

@Override
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);
}

public void set(String name, int age)
{
this.name = name;
this.age = age;
}

public void set(Person other)
{
this.name = other.name;
this.age = other.age;
}

public Person clone()
{
Person p = new Person(this.name, this.age);
return p;
}

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

public int compareTo(Person other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Person)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {

public int compare(Person p1, Person p2) {

int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

}

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

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

@Override
public boolean equals(Object other)                             // Object.equals overriding
{
if (other instanceof Student) {
Student that = (Student) other;
return that.canEqual(this) && this.getName().equals(that.getName()) && this.getAge() == that.getAge() && this.getID() == that.getID();
}
return false;
}

@Override
public int hashCode() {
return (41 * super.hashCode() + getID());
}

public boolean canEqual(Object other) {
return (other instanceof Student);
}

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

public void superPrint()
{
super.print();
}

public void print() // Person class print() method overriding
{
System.out.println(“Student Name: ” + name + ” Age: ” + age + ” 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 Person)
super.set(other);
else
this.set((Student)other);
}

public Student clone()
{
Student s = new Student(this.name, this.age, this.id);
return s;
}

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

public int compareTo(Student other)
{
String thisName = this.getName().toUpperCase();
String otherName = ((Student)other).getName().toUpperCase();

//ascending order
return thisName.compareTo(otherName);
//descending order
//return otherName.compareTo(thisName);
}

public static Comparator<Student> AgeComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int age1 = p1.getAge();
int age2 = p2.getAge();

//ascending order
return age1 – age2;

//descending order
//return age2 – age1;
}

};

public static Comparator<Student> IDComparator
= new Comparator<Student>() {
public int compare(Student p1, Student p2) {
int id1 = p1.getID();
int id2 = p2.getID();

//ascending order
return id1 – id2;

//descending order
//return id2 – id1;
}

};
}

class PersonStudentTest
{

public static void print(Object[] array) {
for(Object o : array) {
System.out.println(o);
}
}

public static void main(String[] args)
{

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

Student[] sList = new Student[3];
sList[0] = new Student(“Kevin”, 0, 222);
sList[1] = new Student(“Jason”, 1, 333);
sList[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (DEFAULT)!!!”);
Arrays.sort(sList);
print(sList);

System.out.println(“STUDENT SORT by AGE!!!”);
Arrays.sort(sList, Student.AgeComparator);
print(sList);

System.out.println(“STUDENT SORT by ID!!!”);
Arrays.sort(sList, Student.IDComparator);
print(sList);

///////////////////////////////////////////////////////////////////////
Student[] sList2 = new Student[3];
sList2[0] = new Student(“Kevin”, 0, 222);
sList2[1] = new Student(“Jason”, 1, 333);
sList2[2] = new Student(“John”, 2, 111);

System.out.println(“STUDENT SORT BY NAME (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getName().toUpperCase().compareTo(s2.getName().toUpperCase());
}
});
print(sList2);

System.out.println(“STUDENT SORT by AGE (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getAge() – s2.getAge();
}
});
print(sList2);

System.out.println(“STUDENT SORT by ID (anonymous method)!!!”);
Arrays.sort(sList2, new Comparator<Student>() {
public int compare(Student s1, Student s2) {
return s1.getID() – s2.getID();
}
});
print(sList2);

///////////////////////////////////////////////////////////////////////
Student[] sList3 = sList2;

System.out.println(“STUDENT SORT BY NAME (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by AGE (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getAge(), ss2.getAge())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

System.out.println(“STUDENT SORT by ID (lambda)!!!”);
Arrays.sort(sList3, (Student ss1, Student ss2) ->
Integer.compare(ss1.getID(), ss2.getID())
);
Arrays.stream(sList3).forEach((s) -> System.out.println(s));

///////////////////////////////////////////////////////////////////////
List<Student> sList4 = new ArrayList<Student>();

System.out.println(“STUDENTLIST SORT BY NAME (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getName().compareTo(ss2.getName())
);
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by AGE (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getAge() – ss2.getAge()
);
sList4.forEach((s) -> System.out.println(s));

System.out.println(“STUDENTLIST SORT by ID (lambda)!!!”);
sList4.sort((Student ss1, Student ss2) ->
ss1.getID() – ss2.getID()
);
sList4.forEach((s) -> System.out.println(s));

}

}

## BMICALCULATOR

표준체중계산기 (BMI Calculator)

– 표준체중
// 남자표준체중 = 신장(m) x 신장(m) x 22
// 여자표준체중 = 신장(m) x 신장(m) x 21

– BMI
// BMI = 체중(kg)/신장^2(m^2)
// 20 미만 저체중 (Underweight)
// 20~24 정상 (Normal)
// 25~29 과체중 (Overweight)
// 30 이상 비만 (Obesity)

– 하루 권장 섭취량
// 한국인 하루권장섭취량 남성 2600 kcal 여성 2100 kcal
// 기초대사량산출공식 (Herris Benedict Equation)
// 기초대사량(남성) = 66.47 + (13.75*weight) + (5*height) – (6.76*age)
// 기초대사량(여성) = 655.1 + (9.05*weight) + (1.85*height) – (4.68*age)
// 활동대사량 = 저활동적(1.3)/중간활동적(1.5)/활동적(1.75)
// 개인별 하루권장섭취량(kcal) = 기초대사량 * 활동대사량

enum BMI {
UNDERWEIGHT, NORMAL, OVERWEIGHT, OBESITY
}

enum Gender {
FEMALE, MALE
}

enum Activity {
LOW, MEDIUM, HIGH;

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

public static Activity valueOf(int value)
{
switch(value) {
case 0:
return LOW;
case 1:
return MEDIUM;
case 2:
return HIGH;
default:
return null;
}
}
}

public class BMICalculator {

public int age = 20;
public double height = 165;
public double weight = 55;
public Gender gender = Gender.FEMALE;
public Activity activity = Activity.MEDIUM;

public BMICalculator()
{
this(20, 165.0, 55.0, Gender.FEMALE, Activity.MEDIUM);
}

public BMICalculator(int age, double height, double weight, Gender gender, Activity activity)
{
this.age = age;
this.height = height;
this.weight = weight;
this.gender = gender;
this.activity = activity;
}

public BMI calculateBMI()
{
double bmi = weight / (height * 0.01) / (height * 0.01);
if (bmi >= 0.0 && bmi < 20.0)
{
return BMI.UNDERWEIGHT;
}
else if (bmi >= 20.0 && bmi < 24.0)
{
return BMI.NORMAL;
}
else if (bmi >= 24.0 && bmi < 30.0)
{
return BMI.OVERWEIGHT;
}
else
{
return BMI.OBESITY;
}
}

public double calculateStandardWeight()
{
if (this.gender == Gender.MALE) {
return height * height * 22 * 0.0001;
}
return height * height * 21 * 0.0001;
}

// Herris Benedict Equation
public double calculateDailyCaloryIntake()
{
double activityCalory = 1.0;
switch (this.activity)
{
case LOW:
activityCalory = 1.3;
case MEDIUM:
activityCalory = 1.5;
case HIGH:
activityCalory = 1.75;
}

if (this.gender == Gender.MALE) {
return 66.47 + (13.75 * this.weight) + (5.0 * this.height) – (6.76 * (double)(this.age)) * activityCalory;
}
return 655.1 + (9.05 * this.weight) + (1.85 * this.height) – (4.68 * (double)(this.age)) * activityCalory;
}
}

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

JLabel label1 = new JLabel(“나이”); // 레이블 초기화
JLabel label2 = new JLabel(“키(cm)”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게(kg)”); // 레이블 초기화
JLabel label4 = new JLabel(“성별”); // 레이블 초기화
JLabel label5 = new JLabel(“활동량”); // 레이블 초기화
JTextField textfield1 = new JTextField(10); // age 텍스트필드 초기화
JTextField textfield2 = new JTextField(10); // height 텍스트필드 초기화
JTextField textfield3 = new JTextField(10); // weight 텍스트필드 초기화
String[] names = {“Low”, “Medium”, “High”};
JComboBox<String> combobox1 = new JComboBox<String>(names); // acitivity 콤보박스

JButton button1 = new JButton(“계산”); // bmi calculator 버튼 초기화

JLabel label6 = new JLabel(“BMI 지수”); // 레이블 초기화
JLabel label7 = new JLabel(“정상 몸무게”); // 레이블 초기화
JLabel label8 = new JLabel(“일일 칼로리섭취량”); // 레이블 초기화
JTextField textfield4 = new JTextField(10); // bmi 텍스트필드 초기화
JTextField textfield5 = new JTextField(10); // standard weight 텍스트필드 초기화
JTextField textfield6 = new JTextField(10); // dailry calory intake 텍스트필드 초기화

JPanel panel = new JPanel(); // 패널 초기화
JPanel panel1 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel2 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel3 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel4 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel5 = new JPanel(); // 패널 초기화
JPanel panel6 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel7 = new JPanel(); // 패널 초기화
JPanel panel8 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel9 = new JPanel(new GridLayout(0, 2)); // 패널 초기화
JPanel panel10 = new JPanel(new GridLayout(0, 2)); // 패널 초기화

public BMICalculatorFrame() {
super(“BMICalculatorFrame”);

// frame