HW4

HW4 – DateTime Parse

private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

// use comma as separator
String[] items = line.split(delimiter);
Date dateTime = null;
try {
      dateTime = formatter.parse(items[0]);
}
catch (ParseException e) {
      e.printStackTrace();
}

/////////////////////////DateParseTest.java////////////////////////////////////////

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.io.FileNotFoundException;
import java.util.*;

public class DateParseTest {
 private static final SimpleDateFormat formatter = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

 public static void main(String[] args)  {
  String date=”1980-12-29 13:00:06″;

  Date dateTime = null;
  try {
   dateTime = formatter.parse(date);
  }
  catch (ParseException e) {
   e.printStackTrace();
  }
  System.out.println(formatter.format(dateTime));
 }
}

Person FileIO & JTable

Person ArrayList & FileIO & JTable & CustomDialog & Menu

1. Person 클래스

import java.util.*;

enum Gender
{
FEMALE, MALE
}

public class Person implements Comparable<Person>
{
private String name;
private int age;
private double weight;
private double height;
private Gender gender;

public Person()
{
this(“”, 0, 0.0, 0.0, Gender.FEMALE);
}

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

public Person(Person other)
{
this(other.name, other.age, other.weight, other.height, other.gender);
}

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 double getWeight()
{
return weight;
}

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

public double getHeight()
{
return height;
}

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

public Gender getGender()
{
return gender;
}

public void setGender(Gender gender)
{
this.gender = gender;
}

@Override
public String toString() // Object.toString() overriding
{
return String.format(“%s,%d,%.2f,%.2f,%s”, name, age, weight, height, gender.toString());
}

@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()
&& this.getWeight() == that.getWeight()
&& this.getHeight() == that.getHeight()
&& this.getGender() == that.getGender();
}
return false;
}

@Override
public int hashCode()
{
return (41 * getName().hashCode() + getAge() + Double.valueOf(getWeight()).hashCode() + Double.valueOf(getHeight()).hashCode() + (int)(getGender()).hashCode());
}

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

public int compareTo(Person other)
{
return this.getName().compareTo(other.getName()); //ascending order
}

public static Comparator<Person> AgeComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getAge() – p2.getAge(); //ascending order
}
};

public static Comparator<Person> WeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getWeight(), p2.getWeight()); //ascending order
}
};

public static Comparator<Person> HeightComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return Double.compare(p1.getHeight(), p2.getHeight()); //ascending order
}
};

public static Comparator<Person> GenderComparator
= new Comparator<Person>() {
public int compare(Person p1, Person p2) {
return p1.getGender().compareTo(p2.getGender());
}
};

}

2. PersonDialog 클래스

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

//Kyoung Shin Park (2016 Fall)
public class PersonDialog extends JDialog implements ActionListener {

public final static int OK = 1;
public final static int CANCEL = 2;
int returnValue = 0;

JLabel label1 = new JLabel(“이름”); // 레이블 초기화
JLabel label2 = new JLabel(“나이”); // 레이블 초기화
JLabel label3 = new JLabel(“몸무게”); // 레이블 초기화
JLabel label4 = new JLabel(“키”); // 레이블 초기화
JLabel label5 = new JLabel(“성별”); // 레이블 초기화

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

JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
ButtonGroup rgroup = new ButtonGroup();
JPanel panel = new JPanel(); // 패널 초기화

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

Person person = new Person();

public PersonDialog() {
setTitle(“Person Dialog”);
setLayout(null);

// frame
label1.setBounds(20, 30, 100, 20);
label2.setBounds(20, 60, 100, 20);
label3.setBounds(20, 90, 100, 20);
label4.setBounds(20, 120, 100, 20);
label5.setBounds(20, 150, 100, 20);
add(label1);
add(label2);
add(label3);
add(label4);
add(label5);

textfield1.setBounds(120, 30, 150, 20);
textfield2.setBounds(120, 60, 150, 20);
textfield3.setBounds(120, 90, 150, 20);
textfield4.setBounds(120, 120, 150, 20);

add(textfield1);
add(textfield2);
add(textfield3);
add(textfield4);
panel.add(rbutton1);
panel.add(rbutton2);
rgroup.add(rbutton1);
rgroup.add(rbutton2);
panel.setBounds(20, 150, 300, 40);
add(panel);

button1.setBounds(60, 200, 160, 20);
add(button1);

// event
button1.addActionListener(this);

setSize(300, 270); // size the frame
setResizable(false);
setModal(true);
}

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

public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button == button1) {
person.setName(textfield1.getText());
person.setAge(Integer.parseInt(textfield2.getText()));
person.setWeight(Double.parseDouble(textfield3.getText()));
person.setHeight(Double.parseDouble(textfield4.getText()));
person.setGender(selectGender());
returnValue = OK;
dispose();
}
}

public int getReturnValue()
{
return returnValue;
}

public Person getPerson()
{
return person;
}

/*public static void main(String[] args) {
new PersonDialog();
}*/
}

3. PersonTableModel 클래스

import java.util.*;
import javax.swing.table.*;

public class PersonTableModel extends AbstractTableModel {

private ArrayList<Person> personList;

public PersonTableModel(ArrayList<Person> pList) {
this.personList = new ArrayList<Person>(pList);
}

@Override
public int getRowCount() {
return this.personList.size();
}

@Override
public int getColumnCount() {
return 5;
}

@Override
public String getColumnName(int column) {
String name = “??”;
switch (column) {
case 0:
name = “Name”;
break;
case 1:
name = “Age”;
break;
case 2:
name = “Weight”;
break;
case 3:
name = “Height”;
break;
case 4:
name = “Gender”;
break;
}
return name;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
Class<?> type = String.class;
switch (columnIndex) {
case 0:
type = String.class;
break;
case 1:
type = Integer.class;
break;
case 2:
case 3:
type = Double.class;
break;
case 4:
type = Gender.class;
break;
}
return type;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Person p = this.personList.get(rowIndex);
Object value = null;
switch (columnIndex) {
case 0:
value = p.getName();
break;
case 1:
value = p.getAge();
break;
case 2:
value = p.getWeight();
break;
case 3:
value = p.getHeight();
break;
case 4:
value = p.getGender();
break;
}
return value;
}

public void setValueAt(Person value, int rowIndex) {
this.personList.set(rowIndex, value);
fireTableDataChanged();
}

public void addRow(Person p) {
this.personList.add(p);
fireTableRowsInserted(this.personList.size() – 1, this.personList.size() – 1);
}

public void removeRow(int rowIndex) {
if (rowIndex >=0 && rowIndex < getRowCount()) {
this.personList.remove(rowIndex);
fireTableRowsDeleted(rowIndex, rowIndex);
}
}
}

4. PersonTableFrame 클래스

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

//Kyoung Shin Park (2016 Fall)
public class PersonTableFrame extends JFrame {

ArrayList<Person> personList = new ArrayList<Person>();
PersonTableModel model;

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

model = new PersonTableModel(personList);
JTable table = new JTable(model);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.setIntercellSpacing(new Dimension(10, 5));
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent evt) {
int index = table.getSelectedRow();
if (index >= 0 && index < personList.size()) {
personList.remove(index);
model.removeRow(index);
//personList.forEach((s) -> System.out.println(s));
}
}
});
/*.add(new Person(“Dooly”, 1000, 40, 126.4, Gender.MALE));
personList.add(new Person(“Douner”, 1986, 30, 110, Gender.MALE));
personList.add(new Person(“Ddochi”, 30, 50, 150.5, Gender.MALE));
personList.add(new Person(“Heedong”, 3, 36, 100.6, Gender.MALE));
personList.add(new Person(“Michol”, 25, 39.8, 126.4, Gender.MALE));
personList.add(new Person(“Gildong”, 40, 38.2, 129.4, Gender.MALE));
personList.add(new Person(“Younghi”, 10, 47.2, 152.4, Gender.FEMALE));
personList.add(new Person(“Cheolsoo”, 10, 48.2, 155.4, Gender.MALE));
personList.forEach((s) -> System.out.println(s));
personList.forEach((s) -> model.addRow(s));*/

personList = loadCSV(“data/PersonList.csv”);
personList.forEach((s) -> model.addRow(s));
//personList.forEach((s) -> System.out.println(s));
//saveCSV(“TestList.csv”, personList);

JScrollPane scrollPane = new JScrollPane(table);
this.add(scrollPane, BorderLayout.CENTER);

// menu
JMenuBar menuBar = new JMenuBar();

// File Menu, F – Mnemonic
JMenu fileMenu = new JMenu(“File”);
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);

// File->Open, O – Mnemonic
JMenuItem openMenuItem = new JMenuItem(“Open”, KeyEvent.VK_O);
fileMenu.add(openMenuItem);
this.setJMenuBar(menuBar);
openMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“OPEN”);
String selectedFilename = openFileDialog();
if (selectedFilename != null) {
personList = loadCSV(selectedFilename);
personList.forEach((q) -> model.addRow(q));
}
}
});

// File->Save, O – Mnemonic
JMenuItem saveMenuItem = new JMenuItem(“Save”, KeyEvent.VK_S);
fileMenu.add(saveMenuItem);
this.setJMenuBar(menuBar);
saveMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.out.println(“SAVE”);
String selectedFilename = saveFileDialog();
if (selectedFilename != null) {
saveCSV(selectedFilename, personList);
}
}
});

// File->Exit, E – Mnemonic
JMenuItem exitMenuItem = new JMenuItem(“Exit”, KeyEvent.VK_E);
fileMenu.add(exitMenuItem);
this.setJMenuBar(menuBar);
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
System.exit(0);
}
});

// Person Menu, P – Mnemonic
JMenu personMenu = new JMenu(“Person”);
personMenu.setMnemonic(KeyEvent.VK_P);
menuBar.add(personMenu);

// Person->Add, A – Mnemonic
JMenuItem addMenuItem = new JMenuItem(“Add”, KeyEvent.VK_A);
personMenu.add(addMenuItem);
this.setJMenuBar(menuBar);
addMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent event) {
PersonDialog personDialog = new PersonDialog();
personDialog.setVisible(true);
if (personDialog.getReturnValue() == PersonDialog.OK) {
Person p = personDialog.getPerson();
//System.out.println(p);
model.addRow(p);
personList.add(p);
System.out.println(“After add:”);
personList.forEach((s) -> System.out.println(s));
System.out.println(“———————added”);
}
}
});

this.setSize(600, 450);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public String openFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“openFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not opened”);
return null;
}
}

public String saveFileDialog() {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
System.out.println(“saveFile”);
String selectedFilename = fileChooser.getSelectedFile().getAbsolutePath().toString();
System.out.println(selectedFilename);
return selectedFilename;
}
else {
System.out.println(“file not selected”);
return null;
}
}

// load CSV
public ArrayList<Person> loadCSV(String filename)
{
ArrayList<Person> pList = new ArrayList<Person>();
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
System.out.println(“file import: ” + filename);

String line = “”;
String delimiter = “,”;

while ((line = br.readLine()) != null) {
// use comma as separator
String[] items = line.split(delimiter);
String name = items[0];
int age = Integer.parseInt(items[1]);
double weight = Double.parseDouble(items[2]);
double height = Double.parseDouble(items[3]);
Gender gender = items[4].equals(“FEMALE”) ? Gender.FEMALE : Gender.MALE;

// add Person into List
Person p = new Person(name, age, weight, height, gender);
//System.out.println(p);
pList.add(p);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(“load successfully”);
return pList;
}

// save CSV
public void saveCSV(String path, ArrayList<Person> pList)
{
FileWriter fw;
try {
System.out.println(“file save: ” + path);

fw = new FileWriter(path);
for (Person p : pList) {
System.out.println(p);
fw.append(p.toString() + “\n”);
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void main(String args[])
{
new PersonTableFrame(); // data table
}

}

KoreaMapViewer

KoreaMapViewer

1. Download JMapViewer-2.0
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)

javac-classpath

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)

eclipse-configure-buildpath

eclipse-add-jars

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 쿼리를 한 후 새로운 파일에 저장한다. 등등. 실행 화면과 코드를 첨부하시오.

BMICALCULATOR

표준체중계산기 (BMI Calculator)
-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 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 텍스트필드 초기화
JRadioButton rbutton1 = new JRadioButton(“여자”, true); // gender 라디오버튼
JRadioButton rbutton2 = new JRadioButton(“남자”); // gender 라디오버튼
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
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);
}

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

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

Basic

2.Basic
•ArithmeticOperator (+ – * /) method
•TemperatureConverter (F->C or C->F) enum, method, switch, if/else, for, while, do/while, break, continue, try/catch
•BreakContinueTest – break, continue
•FactorialTest (팩토리얼 연산) – recursive call
•BankAccount – class, static/instance method/field
•CheckUserInput (사용자 입력) – do/while, continue, try catch
•Divisor (약수) – for