Lab7

java1-lab7(updated)
Lab7 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (2~3장)를 넣고 Lab7_학번_이름.zip 압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출 (Due by 5/28 연장)

Lab7 package & import & ArrayList & triangle classification & quadrilateral classification

도형의 점을 입력하여 삼각형/사각형 도형을 판별하고 도형의 면적과 둘레를 계산한다.

Lab7 프로젝트 디렉토리 안에 모든 파일(src/*.java & bin/*.class)와 보고서 (2~3장)를 넣고 Lab7_학번_이름.zip 압축한 후 e-learning(http://lms.dankook.ac.kr/index.jsp)으로 제출 (Due by 5/31 연장)

Lab7 package & import & ArrayList & triangle classification & quadrilateral classification

Triangle 클래스

-TriangleType classify()

-TriangleType classifyByAngle()

Quadrilateral 클래스

-QuadrilateralType classify()

-Quadrilateral 클래스의 area()

Lab7 클래스

-ArrayList<Figure> figureList
-그리고, 사용자가 도형의 점을 입력하여 삼각형/사각형 도형을 판별하고 도형의 면적과 둘레를 계산한다.

 

private static final Point[] triangle1 = { new Point(10, 0), new Point(0, 10), new Point(10, 10) };
private static final Point[] triangle2 = { new Point(5, 0), new Point(0, 10), new Point(10, 10) };
private static final Point[] triangle3 = { new Point(7, 0), new Point(0, 5), new Point(5, 5) };
private static final Point[] triangle4 = { new Point(5, 0), new Point(0, 10), new Point(5, 5) };
private static final Point[] triangle5 = { new Point(7, 0), new Point(0, 5), new Point(5, 10) };
private static final Point[] rectPoints1 = { new Point(0, 0), new Point(0, 20), new Point(30, 20), new Point(30, 0) };
private static final Point[] rectPoints2 = { new Point(10, 0), new Point(0, 10), new Point(20, 30), new Point(30, 20) };
private static final Point[] squarePoints1 = { new Point(0, 0), new Point(0, 20), new Point(20, 20), new Point(20, 0) };
private static final Point[] squarePoints2 = { new Point(0, 20), new Point(20, 40), new Point(40, 20), new Point(20, 0) };
private static final Point[] trapezoidPoints1 = { new Point(10, 0), new Point(0, 20), new Point(30, 20), new Point(20, 0) };
private static final Point[] trapezoidPoints2 = { new Point(0, 10), new Point(0, 30), new Point(10, 40), new Point(10, 0) };
private static final Point[] trapezoidPoints3 = { new Point(0, 10), new Point(20, 30), new Point(30, 20), new Point(20, 10) };
private static final Point[] trapezoidPoints4 = { new Point(0, 0), new Point(10, 30), new Point(30, 30), new Point(10, 0)};
private static final Point[] parPoints1 = { new Point(10, 0), new Point(0, 20), new Point(20, 20), new Point(30, 0) };
private static final Point[] parPoints2 = { new Point(10, 10), new Point(30, 10), new Point(20, 0), new Point(0, 0) };
private static final Point[] parPoints3 = { new Point(0, 10), new Point(20, 30), new Point(40, 20), new Point(20, 0) };
private static final Point[] rhombusPoints1 = { new Point(10, 0), new Point(0, 20), new Point(10, 40), new Point(20, 20) };
private static final Point[] rhombusPoints2 = { new Point(20, 0), new Point(0, 10), new Point(20, 20), new Point(40, 10) };
private static final Point[] kitePoints1 = { new Point(10, 0), new Point(0, 10), new Point(10, 40), new Point(20, 10)};
private static final Point[] kitePoints2 = { new Point(10, 0), new Point(0, 10), new Point(10, 20), new Point(40, 10)};

String immutable vs StringBuilder mutable


// String immutable vs. StringBuilder mutable
// + operator (new StringBuilder(String.valueOf(str1)).append(str2).toString();
String a = "Hello";
String b = "Hello";
String c = a;
String d = "Hel" + "lo";
String e = "Hello" + "";
String f = a + ""; // String + StringLiteral => new String
String g = "";
String h = a + g; // String + String -> new String
String s = new String("Hello"); // new String
String t = new String("Hello"); // new String
String u = s + new String(""); // String + String -> new String
String v = s + new String(""); // String + String -> new String
String x = s.concat("~"); // concat creates new String
String y = s.concat("~"); // concat creates new String
System.out.println(getReference(a) + " a=" + a + " hashCode=" + a.hashCode());
System.out.println(getReference(b) + " b=" + b + " hashCode=" + b.hashCode());
System.out.println(getReference(c) + " c=" + c + " hashCode=" + c.hashCode());
System.out.println(getReference(d) + " d=" + d + " hashCode=" + d.hashCode());
System.out.println(getReference(e) + " e=" + e + " hashCode=" + e.hashCode());
System.out.println("a==e " + (a == e));
System.out.println(getReference(f) + " f=" + f + " hashCode=" + f.hashCode());
System.out.println("a==f " + (a == f));
System.out.println(getReference(g) + " g=" + g + " hashCode=" + g.hashCode());
System.out.println(getReference(h) + " h=" + h + " hashCode=" + h.hashCode());
System.out.println("a==h " + (a == h));
System.out.println(getReference(s) + " s=" + s + " hashCode=" + s.hashCode());
System.out.println("a==s " + (a == s));
System.out.println(getReference(t) + " t=" + t + " hashCode=" + t.hashCode());
System.out.println("s==t " + (s == t));
System.out.println(getReference(u) + " u=" + u + " hashCode=" + u.hashCode());
System.out.println(getReference(v) + " v=" + v + " hashCode=" + v.hashCode());
System.out.println("u==v " + (u == v));
System.out.println(getReference(x) + " x=" + x + " hashCode=" + x.hashCode());
System.out.println(getReference(y) + " y=" + y + " hashCode=" + y.hashCode());
System.out.println("x==y " + (x == y));

String str1 = "P";
String str2 = "P";
String str3 = str1 + str2;
String str4 = str1.concat(str2);
System.out.println(getReference(str1) + " str1=" + str1 + " hashCode=" + str1.hashCode());
System.out.println(getReference(str2) + " str2=" + str2 + " hashCode=" + str2.hashCode());
System.out.println(getReference(str3) + " str3=" + str3 + " hashCode=" + str3.hashCode());
System.out.println(getReference(str4) + " str4=" + str4 + " hashCode=" + str4.hashCode());
System.out.println("str3==str4 " + (str3 == str4));

 

 
java.lang.String@5a39699c a=Hello hashCode=69609650
java.lang.String@5a39699c b=Hello hashCode=69609650
java.lang.String@5a39699c c=Hello hashCode=69609650
java.lang.String@5a39699c d=Hello hashCode=69609650
java.lang.String@5a39699c e=Hello hashCode=69609650
a==e true
java.lang.String@3cb5cdba f=Hello hashCode=69609650
a==f false
java.lang.String@56cbfb61 g= hashCode=0
java.lang.String@1134affc h=Hello hashCode=69609650
a==h false
java.lang.String@d041cf s=Hello hashCode=69609650
a==s false
java.lang.String@129a8472 t=Hello hashCode=69609650
s==t false
java.lang.String@1b0375b3 u=Hello hashCode=69609650
java.lang.String@2f7c7260 v=Hello hashCode=69609650
u==v false
java.lang.String@2d209079 x=Hello~ hashCode=-2137068020
java.lang.String@6bdf28bb y=Hello~ hashCode=-2137068020
x==y false
java.lang.String@6b71769e str1=P hashCode=80
java.lang.String@6b71769e str2=P hashCode=80
java.lang.String@2752f6e2 str3=PP hashCode=2560
java.lang.String@e580929 str4=PP hashCode=2560
str3==str4 false

BMICALCULATOR

표준체중계산기 (BMI Calculator)
BMIFrame
-label, button, radiobutton, textfield

– 표준체중
// 남자표준체중 = 신장(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 Person {
    protected String name;
    protected int age;
    protected Gender gender;

    public Person() { 
        this("", 0, Gender.FEMALE); 
    }

    public Person(String name, int age, Gender gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }

    public void setName(String name) { 
        this.name = name; 
    }
    
    public void setAge(int age) { 
	this.age = age; 
    }
    
    public void setGender(Gender gender) { 
	this.gender = gender; 
    }

    public String getName() { 
	return name; 
    }

    public int getAge() { 
 	return age; 
    }

    public Gender getGender() { 
 	return gender; 
    }

    public void print() { 
	System.out.println(this); 
    }

    @Override 
    public String toString() { 
	return "Person Name=" + name + " Age=" + age + " Gender=" + gender; 
    }
}

public class BMICalculator extends Person {
    protected double height;
    protected double weight;
    protected Activity activity;

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

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

    public void setHeight(double height) {
	this.height = height;	
    }
    
    public void setWeight(double weight) {
	this.weight = weight;
    }

    public void setActivity(Activity activity) {
        this.activity = activity;	
    }
    
    public double getHeight() {
	return height;
    }

    public double getWeight() {
	return weight;
    }

    public Activity getActivity() {
	return 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;
            break;
        case MEDIUM:
            activityCalory = 1.5;
            break;
        case HIGH:
            activityCalory = 1.75;
            break;
        default:
            break;
        }

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

    @Override 
    public String toString() { 
	return "BMICalculator Name=" + name + " Age=" + age + " Gender=" + gender + " Height=" + height + " Weight=" + weight + " BMI=" + calculateBMI(); 
    }
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class BMICalculatorFrame extends JFrame implements ActionListener, KeyListener {
    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 텍스트필드 초기화
    JRadioButton rbutton1 = new JRadioButton("여자", true); // gender 라디오버튼
    JRadioButton rbutton2 = new JRadioButton("남자"); // gender 라디오버튼
    JComboBox<String> combobox1 = new JComboBox<String>(Activity.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
        panel1.add(label1);
        panel1.add(textfield1);

        panel2.add(label2);
        panel2.add(textfield2);

        panel3.add(label3);
        panel3.add(textfield3);

        panel5.add(rbutton1);
        panel5.add(rbutton2);
        panel4.add(label4);
        panel4.add(panel5);

        panel6.add(label5);
        panel6.add(combobox1);

        panel7.add(button1);

        panel8.add(label6);
        panel8.add(textfield4);

        panel9.add(label7);
        panel9.add(textfield5);

        panel10.add(label8);
        panel10.add(textfield6);

        panel.add(panel1);
        panel.add(panel2);
        panel.add(panel3);
        panel.add(panel4);
        panel.add(panel6);
        panel.add(panel7);
        panel.add(panel8);
        panel.add(panel9);
        panel.add(panel10);
        add(panel);

        // event
        textfield1.addKeyListener(this);
        textfield2.addKeyListener(this);
        textfield3.addKeyListener(this);
        button1.addActionListener(this);

        setSize(350, 300);
        setResizable(false);
        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private Gender selectGender() {
        if (rbutton1.isSelected() return Gender.FEMALE;
        return Gender.MALE;
    }

    private Activity selectActivity() {
        return Activity.valueOf(combobox1.getSelectedIndex());
    }

    private void calculateStandardWeightAndBMI() {
        calculator.age = Integer.parseInt(textfield1.getText());
        calculator.height = Double.parseDouble(textfield2.getText());
        calculator.weight = Double.parseDouble(textfield3.getText());
        calculator.gender = selectGender();
        calculator.activity = selectActivity();
        System.out.println("age=" + calculator.age);
        System.out.println("height=" + calculator.height);
        System.out.println("weight=" + calculator.weight);
        System.out.println("gender=" + calculator.gender);
        System.out.println("activity=" + calculator.activity);
        BMI bmi = calculator.calculateBMI();
        double sw = calculator.calculateStandardWeight();
        double dailyIntake = calculator.calculateDailyCaloryIntake();
        textfield4.setText("" + bmi);
        textfield5.setText("" + sw);
        textfield6.setText("" + dailyIntake);
    }

    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();
        if (button == button1) {
            calculateStandardWeightAndBMI(); // 계산
        }
    }
    
    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            Toolkit.getDefaultToolkit().beep(); 
            System.out.println("ENTER pressed");
            calculateStandardWeightAndBMI(); // 계산
        }
    }

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

Aridity Index

건조지수(Aridity Index)를 구하고, 기후의 상태를 알려주는 프로그램을 작성한다.
AridityIndexFrame

(1) 사용자에게 연강수량(Precipitation)과 연평균기온(Temperature)를 입력 받는다. 연강수량의 단위는 mm이고, 연평균기온의 단위는 C이다.

(2) 건조지수를 다음 공식으로 계산하고 결과를 화면에 출력한다.
건조지수 De Martonne Aridity Index = Precipitation/ (Temperature + 10)

(3) 다음 기준에 따라 기후의 상태를 판단해서 화면에 출력한다.
AI >= 60 => Perhumid
30 <= AI < 60 => Humid
20 <= AI < 30 => SubHumid
15 <= AI < 20 => SemiArid
5 <= AI < 15 => Arid
AI < 5 => ExtremelyArid

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

//Class: AridityIndexCalculator
public class AridityIndexFrame extends JFrame implements ActionListener, KeyListener {
    JLabel label1 = new JLabel("연평균 온도 (C)"); // 레이블 초기화
    JLabel label2 = new JLabel("강수량 (mm)"); // 레이블 초기화
    JLabel label3 = new JLabel("건조지수 (LA)"); // 레이블 초기화

    JTextField textfield1 = new JTextField("0", 20); // 텍스트필드 초기화
    JTextField textfield2 = new JTextField("0", 20); // 텍스트필드 초기화
    JTextField textfield3 = new JTextField(20); // 텍스트필드 초기화

    JButton button1 = new JButton("확인"); // 버튼 초기화

    JPanel panel = new JPanel(); // 패널 초기화
    JPanel panel1 = new JPanel(); // 패널 초기화
    JPanel panel2 = new JPanel(); // 패널 초기화
    JPanel panel3 = new JPanel(); // 패널 초기화

    public AridityIndexFrame() {
        super("Aridity Index Frame");

        // frame
        panel1.add(label1);
        panel1.add(textfield1);

        panel2.add(label2);
        panel2.add(textfield2);

        panel3.add(label3);
        panel3.add(textfield3);

        panel.add(panel1);
        panel.add(panel2);
        panel.add(panel3);
        panel.add(button1);
        add(panel);

        // event
        textfield1.addKeyListener(this);
        textfield2.addKeyListener(this);
        button1.addActionListener(this);

        setSize(350, 200);
        setResizable(false);
        setVisible(true);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private double ToDouble(String str) {
        return Double.parseDouble(str);
    }

    public void actionPerformed(ActionEvent e) {
        JButton button = (JButton) e.getSource();
        if (button == button1) {
            this.dispose();
        }
    }

    public void keyTyped(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            Toolkit.getDefaultToolkit().beep();
            System.out.println("ENTER pressed");
            JTextField textfield = (JTextField) e.getSource();
            double T = ToDouble(textfield1.getText());
            double P = ToDouble(textfield2.getText());
            textfield3.setText("" + AridityIndexCalculator.Martonne(T, P));
        }
    }

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

ChangeListener, KeyListener, ActionListener

SliderFrame (JSlider, JLabel, JTextfield, JButton)

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

// SliderFrame shows ChangeListener, KeyListener, ActionListener
public class SliderFrame extends JFrame implements ChangeListener, KeyListener, ActionListener {

    JPanel panel = new JPanel(new BorderLayout());
    JPanel panel1 = new JPanel(new FlowLayout());
    JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 100, 20);
    JLabel label = new JLabel("Value : ", JLabel.CENTER);
    JTextField textfield = new JTextField(10);
    JButton button = new JButton("Close");

    public SliderFrame(String name) {
        super(name);

        this.add(panel);
        this.panel1.add(label);
        this.panel1.add(textfield);
        this.panel.add(slider, BorderLayout.CENTER);
        this.panel.add(panel1, BorderLayout.NORTH);
        this.panel.add(button, BorderLayout.SOUTH);

        this.slider.addChangeListener(this); // ChangeListener stateChanged
        this.textfield.addKeyListener(this); // KeyListener keyTyped, keyPressed, keyReleased
        this.button.addActionListener(this); // ActionListener actionPerformed

        this.setSize(250, 150);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

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

    @Override
    public void stateChanged(ChangeEvent e) {
        JSlider s = (JSlider)e.getSource();
        textfield.setText("" + s.getValue()); 
    }

    @Override
    public void keyTyped(KeyEvent e) { 
    }

    @Override
    public void keyPressed(KeyEvent e) {
    }

    @Override
    public void keyReleased(KeyEvent e) {
        int key = e.getKeyCode();
        if (key == KeyEvent.VK_ENTER) {
            Toolkit.getDefaultToolkit().beep(); 
            System.out.println("ENTER pressed");
            JTextField t = (JTextField) e.getSource();
            int value = Integer.parseUnsignedInt(t.getText());
            slider.setValue(value);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton b = (JButton)e.getSource();
        if (b == button) {
            this.setVisible(false);
            this.dispose();
        }
    }
}