====== 수업 과제 정리 ======
[[https://hashcode.co.kr/code_runners?language=java|자바 웹 컴파일러]]
[[프로그램:java:ㄴhomework:quiz|ㄴ과제 퀴즈]]
[[프로그램:java:ㄴhomework:doc|ㄴ개념정리:목차]]
[[프로그램:java:ㄴhomework:book_source|ㄴ북소스]]
===== Hello World 출력 =====
public class HelloWorld{
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
**결과 :**
Hello world!
==== 핵심정리 ====
^ 객체 라이프 사이클 ^
|1. 클래스 정의 |
|2. 객체 참조변수 선언 |
|3. 객체 생성 |
|4. 생성자 호출 |
|5. 주소 할당 |
|6. 객체 사용 |
|7. 객체 소멸 |
^ 코딩 품질향상 단계별 정리 ^||
|1단계| 실행클래스 | main |
|2단계| 헬퍼클래스 | |
|3단계| 상속(Inheritance) | extends |
|4단계| 추상화 | Abstract |
|5단계| Interface | |
|6단계| Implements | |
|7단계| VO | Value Object |
|8단계| 예외처리(Exception) | try ~catch |
|9단계| User-defined | |
|10단계| Multi Thread | |
^품질 1단계 (실행클래스)^
|
class TestStudent {
public static void main(String[] args) {
System.out.println("홍길동");
}
}
|
^품질 2단계 (헬퍼클래스)^
|
class Student {
void doService() {
System.out.println("홍길동");
}
}
|
|
class TestStudent {
public static void main(String[] args) {
Student st = new Student();
st.doService();
}
}
|
^품질 3단계^
|
class Parent { // Super
void doService() {
System.out.println("홍길동");
}
}
|
|
class Student extends Parent {
}
|
|
class TestStudent {
public static void main(String[] args) {
Student st = new Student();
st.doService();
}
}
|
^품질 4단계^
|
abstract class Parent { // Super
abstract void doService();
}
|
|
class Student extends Parent {
void doService() {
System.out.println("홍길동");
}
}
|
|
class TestStudent {
public static void main(String[] args) {
Student st = new Student();
st.doService();
}
}
|
^품질 5단계^
|
interface Parent { // Super
void doService();
}
|
|
class Student implements Parent {
public void doService() {
System.out.println("홍길동");
}
}
|
|
class TestStudent {
public static void main(String[] args) {
Student st = new Student();
st.doService();
}
}
|
^품질 6단계^
|
interface IStudent {
void doService();
}
|
|
class StudentImpl Implements IStudent {
void doService() {
System.out.println(“홍길동”);
}
}
|
|
class Student { // Client
IStudent is;
Student() {
is = new StudentImpl();
}
void doService() {
is.doService();
}
}
|
|
class TestStudent {
public static void main(String[] args) {
Student s = new Student();
s.doService();
}
}
|
^품질 7단계^
|
interface IStudent {
void doService(StudentVO vo);
}
|
|
class StudentImpl implements IStudent {
public void doService(StudentVO vo) {
System.out.println(
vo.getName()+“의 나이는”
+vo.getAge()+“세입니다.”);
}
}
|
|
class Student { // 클라이언트
private IStudent is;
Student(){
is = new StudentImpl();
}
void doService(StudentVO vo) {
is.doService(vo);
}
}
|
|
class StudentVO {
private String name;
private int age;
StudentVO(String name, int age) {
this.name = name;
this.age = age
}
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
void setAge(int age) {
this.age = age
}
int getAge() {
return age;
}
}
|
|
class TestStudent { // 실행클래스
public static void main(String[] args) {
StudentVO vo = new StudentVO(“홍길동”, 20);
Student st = new Student();
st.doService(vo);
}
}
|
^품질 8단계^
|
interface IStudent {
void doService(StudentVO vo);
}
|
|
class StudentImpl implements IStudent {
public void doService(StudentVO vo) throws Exception {
System.out.println(
vo.getName()+“의 나이는”
+vo.getAge()+“세입니다.”);
}
}
|
|
class Student { // 클라이언트
private IStudent is;
Student(){
is = new StudentImpl();
}
void doService(StudentVO vo) {
try {
is.doService(vo);
} catch (Exception c){
System.out.println(c.getMessage());
}
}
}
|
|
class StudentVO {
private String name;
private int age;
StudentVO(String name, int age) {
this.name = name;
this.age = age
}
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
void setAge(int age) {
this.age = age
}
int getAge() {
return age;
}
}
|
|
class TestStudent { // 실행클래스
public static void main(String[] args) {
StudentVO vo;
vo = new StudentVO(“홍길동”, 20);
Student st = new Student();
st.doService(vo);
}
}
|
^품질 9단계^
|
class UserDefinedException extends Exception {
UserDefinedException(String msg){
super(msg);
}
}
|
|
interface IStudent {
void doService(StudentVO vo) throws Exception, UserDefinedException;
}
|
|
class StudentImpl implements IStudent {
public void doService(StudentVO vo) throws Exception, UserDefinedException {
System.out.println(
vo.getName()+“의 나이는”
+vo.getAge()+“세입니다.”);
throw new UserDefinedException(“User-Defined Exception!”);
}
}
|
|
class Student { // 클라이언트
private IStudent is;
Student(){
is = new StudentImpl();
}
void doService(StudentVO vo) {
try {
is.doService(vo);
} catch (UserDefinedException c){
System.out.println(c.getMessage());
} catch (Exception c){
System.out.println(c.getMessage());
}
}
}
|
|
class StudentVO {
private String name;
private int age;
StudentVO(String name, int age) {
this.name = name;
this.age = age
}
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
void setAge(int age) {
this.age = age
}
int getAge() {
return age;
}
}
|
|
class TestStudent { // 실행클래스
public static void main(String[] args) {
StudentVO vo;
vo = new StudentVO(“홍길동”, 20);
Student st = new Student();
st.doService(vo);
}
}
|
|
class IStudent() {
void doService(StduentVO vo);
}
|
|
class StudentImple implements IStudent {
public void doService(StudentVO vo) {
StudentThread st;
st = new StudentThread();
st.start();
}
}
|
|
class StudentThread extends Thread {
StudentVO vo;
StudentThread(StudentVO vo) {
this.vo = vo;
}
void run() {
try{
System.out.println(vo.getName());
} catch(Exception e){
}
}
}
|
|
class Student {
IStudent is;
Student(){
is = new StudentImpl();
}
void doService(StudentVO vo) {
is.doService(vo);
}
}
|
|
class StudentVO {
String name;
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
}
|
|
class TestStudent {
public static void main(String[] args) {
StudentVO vo = new StudentVO();
Student st = new Student();
vo.setName(“홍길동”);
st.doService(vo);
}
}
|
^품질 10단계^
|
class IStudent() {
void doService(StduentVO vo);
}
|
|
class StudentImple implements IStudent {
public void doService(StudentVO vo) {
StudentThread st;
st = new StudentThread();
st.start();
try{
st.join();
} catch(InterruptedException e){
}
}
}
|
|
class StudentThread extends Thread {
StudentVO vo;
StudentThread(StudentVO vo) {
this.vo = vo;
}
void run() {
try{
System.out.println(vo.getName());
} catch(Exception e){
}
}
}
|
|
class Student {
IStudent is;
Student(){
is = new StudentImpl();
}
void doService(StudentVO vo) {
is.doService(vo);
}
}
|
|
class StudentVO {
String name;
void setName(String name) {
this.name = name;
}
String getName() {
return name;
}
}
|
|
class TestStudent {
public static void main(String[] args) {
StudentVO vo = new StudentVO();
Student st = new Student();
vo.setName(“홍길동”);
st.doService(vo);
}
}
|
**주요개념**
for loop
상속 - 멤버필드 : 멤버메소드
**is a** vs **has a**
오버로딩 vs 오버라이딩
==== 문자열 출력하기 (FooBarBaz 01) ====
**System.out.println(" ")라인 출력하기 **
**"\n" 줄 칸 띄우기**
++++System.out.println(" ");|
public class FooBarBaz {
public static void main(String[] args) {
System.out.println(" 1");
System.out.println(" 2");
System.out.println(" 3 foo");
System.out.println(" 4");
System.out.println(" 5 bar");
System.out.println(" 6 foo");
System.out.println(" 7 baz");
System.out.println(" 8");
System.out.println(" 9 foo");
System.out.println("10 bar");
System.out.println("11");
System.out.println("12 foo");
System.out.println("13");
System.out.println("14 baz");
System.out.println("15 foo bar");
System.out.println("16\n");
System.out.println("and so on.");
}
}
++++
++++결과 :|
1
2
3 foo
4
5 bar
6 foo
7 baz
8
9 foo
10 bar
11
12 foo
13
14 baz
15 foo bar
16
and so on.
++++
==== for~ if 문, 반복문 활용 (FooBarBaz 02)====
***System.out.printf("제어문자", Data);**
***%c(문자) %d(정수) %f(실수) %s(문자열)**
System.out.printf("%4s", "문자열");
//문자의 자릿수를 정해줌.
for 구문\\
for(변수 선언; 변수의 사용범위; 변수에 대한 명령){}
for(int i=0; i<10; i++){
if 구문을 통한 반복되는 문자열 추가
if (i % 3 == 0) {
System.out.printf("%4s", "foo")
++++ for~ if 반복문|
public class ForIfEx {
public static void main(String[] args) {
for (int i = 1; i < 17; i ++) {
System.out.printf("%2d", i);
if (i % 3 == 0) {
System.out.printf("%4s", "foo");
}
if (i % 5 == 0) {
System.out.printf("%4s", "bar");
}
if (i % 7 == 0) {
System.out.printf("%4s", "baz");
}
System.out.println();
}
System.out.printf("\nand so on.");
}
}
++++
++++결과 :|
1
2
3 foo
4
5 bar
6 foo
7 baz
8
9 foo
10 bar
11
12 foo
13
14 baz
15 foo bar
16
and so on.
++++
====if ~else문 > 삼항연산자 (학점계산기 01)====
**학점 계산기를 만들기 위한 값의 구조**
^90> A 이고 98>"+" , 94<"-"^
^80~89 = B 이고 88>"+" , 84<"-" ^
| 나머지는 C (default) |
if A(if +) 그 밖은(-) else / 범위의 밖에서부터 생각한다.
grade(문자 변수)+(붙여주는)="+" , "_"
int score = 82; //점수 선언
String grade =" "; // 학점 결과 값 출력을 위한 정의(문자열)
if (score >= 90) { // score가 90점 보다 같거나 크면 A학점(grade) / 1번 if
grade = "A";
if ( score >= 98) { // 90점 이상 중에서도 98점 이상은 A+
grade += "+"; // grade = grade + "+";와 같다.
}else if
grade +="-";
}
++++if ~else|
class FlowEx5 {
public static void main(String[] args) {
int score = 82;
String grade =""; // 두 문자를 저장할 것이므로 변수의 타입을 String으로 함.
System.out.println("당신의 점수는 " + score + "입니다.");
if (score >= 90) { // score가 90점 보다 같거나 크면 A학점(grade)
grade = "A";
if ( score >= 98) { // 90점 이상 중에서도 98점 이상은 A+
grade += "+"; // grade = grade + "+";와 같다.
} else if ( score < 94) {
grade += "-";
}
} else if (score >= 80){ // score가 80점 보다 같거나 크면 B학점(grade)
grade = "B";
if ( score >= 88) {
grade += "+";
} else if ( score < 84) {
grade += "-";
}
} else { // 나머지는 C학점(grade)
grade = "C";
}
System.out.println("당신의 학점은 " + grade + "입니다.");
}
}
++++
**삼항연산자**
grade =
| (score >= 90) ? A + ( (score >= 98) ? "+" : (score < 94) ? "-" ) : " " | (score >= 80) ? B + ( ? "+" : "-" ) : | C |
++++삼항연산자|
ppublic class FlowEx5 {
public static void main(String[] args) {
int score = 82;
String grade = "";
System.out.println("당신의 점수는 " + score + "입니다.");
grade = (score >= 90) ? "A" + ((score >= 98) ? "+"
: (score < 94) ? "-" : "")
: (score >= 80) ? "B" + ((score >= 88) ? "+"
: (score < 94) ? "-" : "")
: "C";
System.out.println("당신의 학점은 " + grade + "입니다.");
}
}
++++
**결과 :**
당신의 점수는 82점입니다.
당신의 학점은 B-입니다.
====switch문 > if ~else문 (점수-상품 01)====
int score = (int)(Math.random()*10+1);
/*
Math.random()*10 -> 0~에서 9.9 사이의 실수를 만들어 냄
(int)를 붙여줘서 소수점을 잘라내고 정수로 변환
*/
^ int score = (int)(Math.random()*10+1); score에 1~10 랜덤 수를 대입 ||||^
| switch(score*100){ |^ case 200 : 실행 break; case 300 : 실행 break; ^| default; 실행 } |
switch(score*100){ // 일종의 분배기
case 100 :
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
break;
++++switch |
class FlowEx6 {
public static void main(String[] args) {
// Math클래스의 random()함수를 이용해서 1~10사이의 값을 얻어낼 수 있다.
int score = (int)(Math.random()*10+1);
switch(score*100) {
case 100 :
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
break;
case 200 :
System.out.println("당신의 점수는 200이고, 상품은 TV입니다.");
break;
case 300 :
System.out.println("당신의 점수는 300이고, 상품은 노트북입니다.");
break;
case 400 :
System.out.println("당신의 점수는 400이고, 상품은 자동차입니다.");
break;
default :
System.out.println("죄송하지만 당신의 점수에 해당상품이 없습니다.");
}
}
}
++++
if(score*100 == 100) {
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
}//switch => if
else if(score*100 == 200) {
System.out.println("당신의 점수는 200이고, 상품은 TV입니다.");
++++if ~else if|
public class FlowEx6 {
public static void main(String[] args) {
int score = (int)(Math.random()*10) + 1;
if(score*100 == 100) {
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
}
else if(score*100 == 200) {
System.out.println("당신의 점수는 200이고, 상품은 TV입니다.");
}
else if(score*100 == 300) {
System.out.println("당신의 점수는 300이고, 상품은 노트북입니다.");
}
else if(score*100 == 400) {
System.out.println("당신의 점수는 400이고, 상품은 자동차입니다.");
}
else {
System.out.println("죄송하지만 당신의 점수에 해당상품이 없습니다.");
}
}
}
++++
**결과 :**
당신의 점수는 100이고, 상품은 자전거입니다.
당신의 점수는 200이고, 상품은 TV입니다.
당신의 점수는 300이고, 상품은 노트북입니다.
당신의 점수는 400이고, 상품은 자동차입니다.
죄송하지만 당신의 점수는 해당상품이 없습니다.
==== switch문 > 삼항연산자 (점수-상품 02) ====
++++switch|
class FlowEx6 {
public static void main(String[] args) {
// Math클래스의 random()함수를 이용해서 1~10사이의 값을 얻어낼 수 있다.
int score = (int)(Math.random() * 10) + 1;
switch(score*100) {
case 100 :
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
break;
case 200 :
System.out.println("당신의 점수는 200이고, 상품은 TV입니다.");
break;
case 300 :
System.out.println("당신의 점수는 300이고, 상품은 노트북입니다.");
break;
case 400 :
System.out.println("당신의 점수는 400이고, 상품은 자동차입니다.");
break;
default :
System.out.println("죄송하지만 당신의 점수에 해당상품이 없습니다.");
}
}
}
++++
++++삼항연산자|
class FlowEx6 {
public static void main(String[] args) {
int score = (int)(Math.random() * 10) + 1;
String str = (score*100 == 100) ? "당신의 점수는 100이고, 상품은 자전거입니다." :
(score*100 == 200) ? "당신의 점수는 200이고, 상품은 TV입니다." :
(score*100 == 300) ? "당신의 점수는 300이고, 상품은 노트북입니다." :
(score*100 == 400) ? "당신의 점수는 400이고, 상품은 자동차입니다." :
"죄송하지만 당신의 점수에 해당상품이 없습니다.";
System.out.println(str);
}
}
++++
**결과 :**
당신의 점수는 100이고, 상품은 자전거입니다.
당신의 점수는 200이고, 상품은 TV입니다.
당신의 점수는 300이고, 상품은 노트북입니다.
당신의 점수는 400이고, 상품은 자동차입니다.
죄송하지만 당신의 점수는 해당상품이 없습니다.
==== switch문 > if ~else문 (학점계산기 02)====
++++switch|
class FlowEx7 {
public static void main(String[] args) {
// 'A', 'B', 'C', 'D' 중의 하나를 얻을 수 있다.
char ch = (char)(Math.random() * 4 + 'A');
int score = 0;
switch (ch) {
case 'A':
score = 90;
break;
case 'B':
score = 80;
break;
case 'C':
score = 70;
break;
case 'D':
score = 60;
break;
}
System.out.println("당신의 점수는 "+ score +"점 이상 입니다.");
}
}
++++
++++if ~else|
public class FlowEx7
public static void main(String[] args) {
char ch = (char)(Math.random() * 4 + 'A');
int score = 0;
if(ch == 'A') {
score = 90;
}
else if(ch == 'B') {
score = 80;
}
else if(ch == 'C') {
score = 70;
}
else if(ch == 'D') {
score = 60;
}
System.out.println("당신의 점수는 "+score+"점 이상 입니다.");
}
}
++++
**결과**
당신의 점수는 90점 이상입니다.
당신의 점수는 80점 이상입니다.
당신의 점수는 70점 이상입니다.
당신의 점수는 60점 이상입니다.
==== switch문 > 삼항연산자 (학점계산기 03) ====
++++switch|
class FlowEx7 {
public static void main(String[] args) {
// 'A', 'B', 'C', 'D' 중의 하나를 얻을 수 있다.
char ch = (char)(Math.random() * 4 + 'A');
int score = 0;
switch (ch) {
case 'A':
score = 90;
break;
case 'B':
score = 80;
break;
case 'C':
score = 70;
break;
case 'D':
score = 60;
break;
}
System.out.println("당신의 점수는 "+ score +"점 이상 입니다.");
}
}
++++
++++삼항연산자|
class FlowEx7 {
public static void main(String[] args) {
char ch = (char)(Math.random() * 4 + 'A');
int score = 0;
if(ch == 'A') {
score = 90;
}
else if(ch == 'B') {
score = 80;
}
else if(ch == 'C') {
score = 70;
}
else if(ch == 'D') {
score = 60;
}
System.out.println("당신의 점수는 "+score+"점 이상 입니다.");
}
}
++++
**결과 :**
당신의 점수는 90점 이상입니다.
당신의 점수는 80점 이상입니다.
당신의 점수는 70점 이상입니다.
당신의 점수는 60점 이상입니다.
==== 품질 1단계 if ~else (계산기 프로젝트 01) ====
**argument 입력**
{{ :programmer:arg01.png?600 | 메뉴 - Run Configrations 선택}}
{{ :programmer:arg02.png?600 | Arguments 탭을 선택해서 Program arguments 칸에 "3 add 5" 입력}}
++++if ~else|
public class TestCal {
public static void main(String[] args) { // java TestCal 5 add 3
int op1 = Integer.parseInt(args[0]); // 5
String op = args[1]; // add
int op2 = Integer.parseInt(args[2]); // 3
if(op.equals("add")) {
System.out.println(op1 + op2);
} else if(op.equals("sub")) {
System.out.println(op1 - op2);
} else if(op.equals("mul")) {
System.out.println(op1 * op2);
} else if(op.equals("div")) {
System.out.println(op1 / op2);
}
}
}
++++
**결과 :**
8
==== switch문 > if ~else, 삼항연산자 (점수-상품 03) ====
++++switch|
class FlowEx8 {
public static void main(String[] args) {
int score = 1;
switch(score*100) {
case 100 :
System.out.println("당신의 점수는 100이고, 상품은 자전거입니다.");
case 200 :
System.out.println("당신의 점수는 200이고, 상품은 TV입니다.");
case 300 :
System.out.println("당신의 점수는 300이고, 상품은 노트북입니다.");
case 400 :
System.out.println("당신의 점수는 400이고, 상품은 자동차입니다.");
default :
System.out.println("죄송하지만 당신의 점수에 해당상품이 없습니다.");
}
}
}
++++
++++if ~else|
public class FlowEx8 {
public static void main(String[] args) {
int score = 1;
if(score*100 == 100) {
System.out.println("당신의 점수는 100 이고, 상품은 자전거 입니다.");
} else if(score*100 == 200) {
System.out.println("당신의 점수는 200 이고, 상품은 TV 입니다.");
} else if(score*100 == 300) {
System.out.println("당신의 점수는 300 이고, 상품은 노트북 입니다.");
} else if(score*100 == 400) {
System.out.println("당신의 점수는 400 이고, 상품은 자동차 입니다.");
} else {
System.out.println("죄송하지만 당신의 점수에 해당상품이 없습니다.");
}
}
}
++++
++++삼항연산자|
public class FlowEx8 {
public static void main(String[] args) {
int score = 0;
String str = "";
str = (score*100 == 100) ? "당신의 점수는 100 이고, 상품은 자전거 입니다." :
(score*100 == 200) ? "당신의 점수는 200 이고, 상품은 TV 입니다." :
(score*100 == 300) ? "당신의 점수는 300 이고, 상품은 노트북 입니다." :
(score*100 == 400) ? "당신의 점수는 400 이고, 상품은 자동차 입니다." :
"죄송하지만 당신의 점수에 해당상품이 없습니다.";
System.out.println(str);
}
}
++++
**결과 :**
당신의 점수는 100이고, 상품은 자전거입니다.
당신의 점수는 200이고, 상품은 TV입니다.
당신의 점수는 300이고, 상품은 노트북입니다.
당신의 점수는 400이고, 상품은 자동차입니다.
죄송하지만 당신의 점수는 해당상품이 없습니다.
==== switch문 > if ~else, 삼항연산자 (점수-상품 04) ====
++++switch|
class FlowEx9 {
public static void main(String[] args) {
int score = (int)(Math.random() * 10) + 1;
String msg ="";
score *= 100; // score = score * 100;
msg = "당신의 점수는 " + score + "이고, 상품은 ";
switch(score) {
case 1000 :
msg += "자전거, "; // msg = msg + "자전거, ";
case 900 :
msg += "TV, ";
case 800 :
msg += "노트북, ";
case 700 :
msg += "자전거, ";
default :
msg += "볼펜";
}
System.out.println( msg + "입니다.");
}
}
++++
++++if ~else|
public class FlowEx9 {
public static void main(String[] args) {
int score = (int)(Math.random()*10)+1;
String msg = "";
score *= 100;
msg = "당신의 점수는" + score +"이고, 상품은 ";
if(score == 1000) {
msg += "자전거";
} else if(score == 900) {
msg += "TV";
} else if(score == 800) {
msg += "노트북";
} else if(score == 700) {
msg += "자전거";
} else {
msg += "볼펜";
}
System.out.println(msg + "입니다.");
}
}
++++
++++삼항연산자|
public class Exercise010_2 {
public static void main(String[] args) {
int score = (int)(Math.random()*10)+1;
String msg = "";
score *= 100;
msg = "당신의 점수는" + score +"이고, 상품은 ";
msg += (score == 1000) ? "자전거" :
(score == 900) ? "TV" :
(score == 800) ? "노트북" :
(score == 700) ? "자전거" :
"볼펜";
System.out.println(msg + "입니다.");
}
}
++++
**결과 :**
당신의 점수는 100이고, 상품은 자전거입니다.
당신의 점수는 200이고, 상품은 TV입니다.
당신의 점수는 300이고, 상품은 노트북입니다.
당신의 점수는 400이고, 상품은 자동차입니다.
죄송하지만 당신의 점수는 해당상품이 없습니다.
==== switch문 > if문, 삼항연산자 (학점계산기 04) ====
++++switch|
class FlowEx10 {
public static void main(String[] args) {
int score = 88;
char grade =' ';
switch(score) {
case 100: case 99: case 98: case 97: case 96:
case 95: case 94: case 93: case 92: case 91:
case 90 :
grade = 'A';
break;
case 89: case 88: case 87: case 86:
case 85: case 84: case 83: case 82: case 81:
case 80 :
grade = 'B';
break;
case 79: case 78: case 77: case 76:
case 75: case 74: case 73: case 72: case 71:
case 70 :
grade = 'C';
break;
case 69: case 68: case 67: case 66:
case 65: case 64: case 63: case 62: case 61:
case 60 :
grade = 'D';
break;
default :
grade = 'F';
} // end of switch
System.out.println("당신의 학점은 " + grade + "입니다.");
} // end of main
} // end of class
++++
++++If ~else|
public class FlowEx10 {
public static void main(String[] args) {
int score = 88;
char grade = ' ';
if(100 >= score || score >= 90) {
grade = 'A';
} else if (89 >= score || score >= 80) {
grade = 'B';
} else if (79 >= score || score >= 70) {
grade = 'C';
} else if (69 >= score || score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
}
}
++++
++++삼항연산자|
public class FlowEx10 {
public static void main(String[] args) {
int score = 88;
char grade = ' ';
grade = (100 >= score || score >= 90) ? 'A' :
(100 >= score || score >= 90) ? 'B' :
(100 >= score || score >= 90) ? 'C' :
(100 >= score || score >= 90) ? 'D' :
'F';
System.out.println(grade);
}
}
++++
**결과 :**
당신의 점수는 90점 이상입니다.
당신의 점수는 80점 이상입니다.
당신의 점수는 70점 이상입니다.
당신의 점수는 60점 이상입니다.
==== switch문 > if문, 삼항연산자 (학점계산기 05) ====
++++switch|
public class FlowEx11 {
public static void main(String[] args) {
int score = 88;
char grade = ' ';
if(score/10 == 10 || score/10 == 9) {
grade = 'A';
} else if(score/10 == 8) {
grade = 'B';
} else if(score/10 == 7) {
grade = 'C';
} else if(score/10 == 6) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("당신의 학점은 " + grade + "입니다.");
}
}
++++
++++if ~else|
public class FlowEx11 {
public static void main(String[] args) {
int score = 88;
char grade = ' ';
if(100 >= score && score >= 90) {
grade = 'A';
} else if(score >= 80) {
grade = 'B';
} else if(score >= 70) {
grade = 'C';
} else if(score >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("당신의 학점은 "+grade+"입니다.");
}
}
++++
++++삼항연산자|
public class FlowEx11 {
public static void main(String[] args) {
int score = 88;
char grade = ' ';
grade = (100 >= score && score >= 90) ? 'A' :
(score >= 80) ? 'B' :
(score >= 70) ? 'C' :
(score >= 60) ? 'D' :
'F';
System.out.println("당신의 학점은 "+grade+"입니다.");
}
}
++++
**결과 :**
당신의 점수는 90점 이상입니다.
당신의 점수는 80점 이상입니다.
당신의 점수는 70점 이상입니다.
당신의 점수는 60점 이상입니다.
==== while > for, do while (구구단 01)====
++++while|
class FlowEx22 {
public static void main(String[] args) {
int i=2;
while(i<=9) {
int j=1;
while(j <=9) {
System.out.println( i +" * "+ j + " = " + i*j );
j++;
}
i++;
} // end of while(i<=9)
}
}
++++
++++for|
class FlowEx22 {
public static void main(String[] args) {
for(int i = 2; i<= 9; i++) {
for(int j = 1; j <= 9; j++) {
System.out.println(i +"*"+j+"="+i*j);
}
}
}
}
++++
++++do ~while|
class FlowEx22 {
public static void main(String[] args) {
int i = 2;
do {
int j = 1;
while(j <= 9) {
System.out.println(i +"*"+j+"="+i*j);
j++;
}
i++;
}while(i <= 9);
}
}
++++
++++결과 : 구구단|
2*1=2
2*2=4
2*3=6
2*4=8
2*5=10
2*6=12
2*7=14
2*8=16
2*9=18
3*1=3
3*2=6
3*3=9
3*4=12
3*5=15
3*6=18
3*7=21
3*8=24
3*9=27
4*1=4
4*2=8
4*3=12
4*4=16
4*5=20
4*6=24
4*7=28
4*8=32
4*9=36
5*1=5
5*2=10
5*3=15
5*4=20
5*5=25
5*6=30
5*7=35
5*8=40
5*9=45
6*1=6
6*2=12
6*3=18
6*4=24
6*5=30
6*6=36
6*7=42
6*8=48
6*9=54
7*1=7
7*2=14
7*3=21
7*4=28
7*5=35
7*6=42
7*7=49
7*8=56
7*9=63
8*1=8
8*2=16
8*3=24
8*4=32
8*5=40
8*6=48
8*7=56
8*8=64
8*9=72
9*1=9
9*2=18
9*3=27
9*4=36
9*5=45
9*6=54
9*7=63
9*8=72
9*9=81
++++
==== while > for, do while (랜덤 숫자 출력)====
++++while|
class FlowEx23 {
public static void main(String[] args) {
int sum =0;
int i = 0;
while(sum + i <= 100) {
sum += ++i; // sum = sum + ++i;
System.out.println(i + " - " + sum);
}
}
}
++++
++++for|
class FlowEx23 {
public static void main(String[] args) {
for(int i = 2; i<= 9; i++) {
for(int j = 1; j <= 9; j++) {
System.out.println(i +"*"+j+"="+i*j);
}
}
}
}
++++
++++do while|
class FlowEx23 {
public static void main(String[] args) {
int i = 2;
do {
int j = 1;
while(j <= 9) {
System.out.println(i +"*"+j+"="+i*j);
j++;
}
i++;
}while(i <= 9);
}
}
++++
++++결과 :|
1-1
2-3
3-6
4-10
5-15
6-21
7-28
8-36
9-45
10-55
11-66
12-78
13-91
++++
==== do ~while > while, for (문자입력)====
++++do ~while|
class FlowEx24 {
public static void main(String[] args) throws java.io.IOException {
int input=0;
System.out.println("문장을 입력하세요.");
System.out.println("입력을 마치려면 x를 입력하세요.");
do {
input = System.in.read();
System.out.print((char)input);
} while(input!=-1 && input !='x');
}
}
++++
++++while|
import java.io.IOException;
class FlowEx24 {
public static void main(String[] args) throws IOException {
int input = 0;
System.out.println("문장을 입력하세요.");
System.out.println("입력을 마치려면 x를 입력하세요.");
input = System.in.read();
System.out.print((char)input);
while(input != -1 && input != 'x'){
input = System.in.read();
System.out.print((char)input);
}
}
}
++++
++++for|
import java.io.IOException;
class FlowEx24 {
public static void main(String[] args) throws IOException {
System.out.println("문장을 입력하세요.");
System.out.println("입력을 마치려면 x를 입력하세요.");
for(int input = 0; ((input != -1) && (input != 'x')); ) {
input = System.in.read();
System.out.print((char)input);
}
}
}
++++
**결과 : **
문장을 입력하세요.
입력을 마치려면 x를 입력하세요.
a
x
==== for > while, do while (10까지의 합 01) ====
++++for|
class FlowEx14 {
public static void main(String[] args) {
int sum =0; // 합계를 저장하기 위한 변수.
int i; // 선언부분을 for문 밖으로 옮겼다.
for(i=1; i <= 10; i++) {
sum += i ; // sum = sum + i;
}
System.out.println( i-1 + " 까지의 합: " + sum);
}
}
++++
++++while|
class FlowEx14 {
public static void main(String[] args) {
int sum = 0;
int i=1;
while(i<=10) {
sum+=i;
i++;
}
System.out.println(i-1 +" 까지의 합: "+sum);
}
}
++++
++++do while|
class FlowEx14 {
public static void main(String[] args) {
int sum = 0;
int i=1;
do {
sum+=i;
i++;
}while(i<=10);
System.out.println(i-1 +" 까지의 합: "+sum);
}
}
++++
**결과**
10까지의 합 : 55
==== 이중 for문 > while, do while (구구단 03)====
++++이중 for문|
class FlowEx16 {
public static void main(String[] args) {
for(int i=2; i <=9; i++) {
for(int j=1; j <=9; j++) {
System.out.println( i +" * "+ j + " = " + i*j );
}
}
}
}
++++
++++중복 while문|
public class FlowEx16 {
public static void main(String[] args) {
int i = 2;
while(i <= 9) {
int j = 1;
while(j <= 9) {
System.out.println(i+" * "+j+" = "+i*j);
j++;
}
i++;
}
}
}
++++
++++do ~while|
public class FlowEx16 {
public static void main(String[] args) {
int i = 2;
do {
int j = 1;
do{
System.out.println(i+" * "+j+" = "+i*j);
j++;
}while(j <= 9);
i++;
}while(i <= 9);
}
}
++++
==== 배열을 이용한 도표 만들기 (01) ====
다음 프로그램을 근거로, 도표를 작성하시오.
++++문제|
class ArrayEx1 {
public static void main(String[] args) {
int sum =0; // 총점을 저장하기 위한 변수
float average = 0f; // 평균을 저장하기 위한 변수
int[] score = {100, 88, 100, 100, 90};
for (int i=0; i < score.length ; i++ ) {
sum += score[i];
}
average = sum / (float)score.length ; // 계산결과를 float로 얻기 위함.
System.out.println("총점 : " + sum);
System.out.println("평균 : " + average);
}
}
----------------------
i score[i] sum
----------------------
0 100 100
1
++++
++++배열|
public class ArrayEx1 {
public static void main(String[] args) {
int sum = 0;
float average = 0f;
int[] score = {100, 88, 100, 100, 90};
System.out.println("------------------");
System.out.println(" i score[i] sum");
System.out.println("------------------");
for(int i = 0; i < score.length; i++) {
sum += score[i];
System.out.printf("%2d %3d %3d\n", i, score[i], sum);
}
average = sum / (float)score.length;
System.out.println("총점 : " + sum);
System.out.println("평균 : " + average);
}
}
++++
==== 배열을 이용한 도표 만들기 (02) ====
다음 프로그램을 근거로, 도표를 작성하시오.
++++문제|
class ArrayEx2 {
public static void main(String[] args) {
int[] score = { 79, 88, 91, 33, 100, 55, 95};
int max = score[0]; // 배열의 첫 번째 값으로 최대값을 초기화 한다.
int min = score[0]; // 배열의 첫 번째 값으로 최소값을 초기화 한다.
for(int i=1; i < score.length;i++) {
if(score[i] > max) {
max = score[i];
}
if(score[i] < min) {
min = score[i];
}
} // end of for
System.out.println("최대값 :" + max);
System.out.println("최소값 :" + min);
} // end of main
} // end of class
-----------------------------
i score[i] max min
-----------------------------
1 88 79 79
2
++++
++++배열|
public class ArrayEx2 {
public static void main(String[] args) {
int[] score = {79, 88, 91, 33, 100, 55, 95};
int max = score[0];
int min = score[0];
System.out.println("--------------------------");
System.out.println(" i score[i] max min");
System.out.println("--------------------------");
for(int i = 1; i < score.length; i++) {
if(score[i] > max) {
max = score[i];
}
if(score[i] < min) {
min = score[i];
}
System.out.printf(" %d %3d %3d %2d\n", i, score[i], max, min);
}// end of for
System.out.println("최대값 : "+max);
System.out.println("최소값 : "+min);
}
}
++++
==== 배열을 이용한 도표 만들기 (03) ====
다음 프로그램을 근거로, 도표를 작성하시오.
++++문제|
class ArrayEx7 {
public static void main(String[] args) {
char[] hex = { 'C', 'A', 'F', 'E'};
String[] binary = { "0000", "0001", "0010", "0011"
, "0100", "0101", "0110", "0111"
, "1000", "1001", "1010", "1011"
, "1100", "1101", "1110", "1111" };
String result="";
for (int i=0; i < hex.length ; i++ ) {
if(hex[i] >='0' && hex[i] <='9') {
result +=binary[hex[i]-'0']; // '8'-'0'의 결과는 8이다.
} else { // A~F이면
result +=binary[hex[i]-'A'+10]; // 'C'-'A'의 결과는 2
}
}
System.out.println("hex:"+ new String(hex));
System.out.println("binary:"+result);
}
}
----------------------------------------------------
i hex[i] binary[hex[i]-'A'+10] result
----------------------------------------------------
0 C 12 1100
1
++++
++++배열|
public class ArrayEx7 {
public static void main(String[] args) {
char[] hex = {'C', 'A', 'F', 'E'};
String[] binary = { "0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111" };
String result = "";
System.out.println("-------------------------------------------------------");
System.out.println(" i hex[i] binary[hex[i]-'A'+10] result");
System.out.println("-------------------------------------------------------");
for(int i = 0; i < hex.length; i++) {
if(hex[i] >= '0' && hex[i] <= '9') {
result += binary[hex[i]-'0'];
} else {
result += binary[hex[i]-'A'+10]; // 공
}
System.out.printf(" %d %c %d "
+ " %s\n", i, hex[i], Integer.parseInt(binary[hex[i]-'A'+10], 2), result);
}
System.out.println("hex:"+new String(hex));
System.out.println("binary:"+result);
}// end of main
}// end of class
++++
==== 배열을 이용한 도표 만들기 (04) ====
다음 프로그램을 근거로, 도표를 작성하시오.
++++문제|
class ArrayEx9 {
public static void main(String[] args) {
String source = "SOSHELP";
String[] morse = {".-", "-...", "-.-.","-..", "."
,"..-.", "--.", "....","..",".---"
, "-.-", ".-..", "--", "-.", "---"
, ".--.", "--.-",".-.","...","-"
, "..-", "...-", ".--", "-..-","-.--"
, "--.." };
String result="";
for (int i=0; i < source.length() ; i++ ) {
result+=morse[source.charAt(i)-'A'];
}
System.out.println("source:"+ source);
System.out.println("morse:"+result);
}
}
--------------------------------------------------------------------------------------------------------
i source source.charAt(i) source.charAt(i)-'A' morse[i] result
--------------------------------------------------------------------------------------------------------
0 SOSHELP S 18 .- ...
1
++++
++++배열|
public class ArrayEx9 {
public static void main(String[] args) {
String source = "SOSHELP";
String[] morse = { ".-", "-...", "-.-.", "-..", ".",
"..-.", "--.", "....", "..", ".---",
"-.-", ".-..", "--", "-.", "---",
".--.", "--.-", ".-.", "...", "-",
"..-", "...-", ".--", "-..-", "-.--",
"--.." };
String result = "";
System.out.println("-------------------------------------------------------------------------------------------");
System.out.println(" i source source.charAt(i) source.charAt(i)-'A' morse[i] result");
System.out.println("-------------------------------------------------------------------------------------------");
for(int i = 0; i ++++
==== 배열을 이용한 도표 만들기 (05) ====
다음 프로그램을 근거로, 도표를 작성하시오.
++++문제|
class ArrayEx10 {
public static void main(String[] args) {
int[][] score = {{ 100, 100, 100}
, { 20, 20, 20}
, { 30, 30, 30}
, { 40, 40, 40}
, { 50, 50, 50}};
int koreanTotal = 0;
int englishTotal = 0;
int mathTotal = 0;
System.out.println("번호 국어 영어 수학 총점 평균 ");
System.out.println("=============================");
for(int i=0;i < score.length;i++) {
int sum=0;
koreanTotal += score[i][0];
englishTotal += score[i][1];
mathTotal += score[i][2];
System.out.print(" " + (i + 1) + " ");
for(int j=0;j < score[i].length;j++) {
sum+=score[i][j];
System.out.print(score[i][j]+" ");
}
System.out.println(sum + " " + sum/(float)score[i].length);
}
System.out.println("=============================");
System.out.println("총점:" + koreanTotal + " " +englishTotal + " " + mathTotal);
}
}
--------------------------------------------------------------------------------------------------------------------
i j score[i][0] score[i][1] score[i][2] score[i][j] sum koreanTotal englishTotal mathTotal
--------------------------------------------------------------------------------------------------------------------
0 0 100 100 100 100 100 100 100 100
0 1
++++
++++배열|
public class ArrayEx10 {
public static void main(String[] args) {
int[][] score = { {100, 100, 100},
{20, 20, 20},
{30, 30, 30},
{40, 40, 40},
{50, 50, 50} };
int koreanTotal = 0;
int englishTotal = 0;
int mathTotal = 0;
//System.out.println("번호 국어 영어 수학 총점 평균");
//System.out.println("==================================");
System.out.print("----------------------------------------------------------");
System.out.println("--------------------------------------------------------");
System.out.print(" i j score[i][0] score[i][1] score[i][2] score[i][j] ");
System.out.println("sum koreanTotal englishTotal mathTotal");
System.out.print("----------------------------------------------------------");
System.out.println("--------------------------------------------------------");
for(int i = 0; i < score.length; i++) {
int sum = 0;
koreanTotal += score[i][0];
englishTotal += score[i][1];
mathTotal += score[i][2];
//System.out.print(" "+(i+1)+" ");
for(int j = 0; j < score[i].length; j++) {
sum += score[i][j];
System.out.printf("%2d %2d %-11d %-11d %-11d %-11d "
, i, j, score[i][0], score[i][1], score[i][2], score[i][j]);
System.out.printf("%3d %-11d %-11d %-11d\n", sum, koreanTotal, englishTotal, mathTotal);
//System.out.print(score[i][j] +" ");
}
//System.out.println(sum+" "+sum/(float)score[i].length);
}
//System.out.println("==================================");
//System.out.println("총점:"+koreanTotal+" "+englishTotal+" "+mathTotal);
}// end of main
}// end of clas
++++
==== 성적처리 표 만들기 (01) ====
++++성적표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
--------------------------------------------------
이름 C# Java HTML5 합 평균
--------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
--------------------------------------------------
총점 ? ? ? ? -
--------------------------------------------------
++++
++++배열|
public class Exercise_23 {
public static void main(String[] args) {
String[] name = {"홍길동", "강감찬", "유관순", "이순신", "김갑순"};
int[][] score = {{90, 80, 70}, // 홍길동
{80, 90, 60}, // 강감찬
{80, 30, 60}, // 유관순
{80, 20, 60}, // 이순신
{70, 90, 60}}; // 김갑순
int[] totalSum = new int[4];
System.out.println("----------------------------------------");
System.out.println("이름 C# JAVA HTML5 합 평균");
System.out.println("----------------------------------------");
for(int i = 0; i < 5; i++) {
System.out.print(name[i]+" ");
int sum = 0;
for(int j = 0; j < 3; j++) {
System.out.printf("%-5d ", score[i][j]);
sum += score[i][j];
totalSum[j] += score[i][j];
totalSum[3] += score[i][j];
}
double avg = (double) sum / 3;
System.out.printf("%5d %.1f\n", sum, avg);
}
System.out.println("----------------------------------------");
System.out.printf("총점 %3d %3d %3d %4d - \n", totalSum[0], totalSum[1], totalSum[2], totalSum[3]);
System.out.print("----------------------------------------");
}// end of main
}// end of class
++++
==== 성적처리 표 만들기 - 석차 (02) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++배열|
public class TestScore {
public static void main(String[] args) {
String[] name = {"홍길동", "강감찬", "유관순", "이순신", "김갑순"};
int[][] score = {{90, 80, 70}, // 홍길동
{80, 90, 70}, // 강감찬
{80, 30, 60}, // 유관순
{80, 20, 60}, // 이순신
{70, 90, 60}}; // 김갑순
int[] rank = new int[5];
int[] sum = new int[5];
double[] avg = new double[5];
int[] totalSum = new int[4]; /* index 0 ~ 2 : 과목별 총합(3과목),
index 3 : 전체 총합 */
// 계산
// 점수(합계, 평균, 총합) 계산
for(int i = 0; i < score.length; i++) {
for(int j = 0; j < score[i].length; j++) {
sum[i] += score[i][j];
totalSum[j] += score[i][j];
totalSum[3] += score[i][j];
}
avg[i] = (double) sum[i] / 3;
}
// 등수 계산
for(int i = 0; i < sum.length; i++) {
int count = sum.length;
for(int j = 0; j < sum.length; j++) {
if(i != j && sum[j] <= sum[i]) {
count--;
}
rank[i] = count;
}
}
// 출력
System.out.println("-------------------------------------------");
System.out.println("이름 C# JAVA HTML5 합 평균 석차");
System.out.println("-------------------------------------------");
for(int i = 0; i < score.length; i++) {
System.out.print(name[i]+" ");
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-5d ", score[i][j]);
}
System.out.printf("%5d %.1f %d\n", sum[i], avg[i], rank[i]);
}
System.out.println("-------------------------------------------");
System.out.printf("총점 %3d %3d %3d %4d - - \n", totalSum[0], totalSum[1], totalSum[2], totalSum[3]);
System.out.println("-------------------------------------------");
}
}
++++
==== 성적처리 표 만들기, 품질 1단계 (03) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++해답|
public class TestScore {
public static void main(String[] args) {
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
int totalSum = 0;
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
// 개인 점수 합, 평균
for(int i = 0; i < score.length-1; i++) {
int sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
double avg = (double)sum / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][4] = sum + "";
score[i][5] = avg+"";
}
// 과목별 합, 전체 합
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
// 개인 석차
for(int i = 0; i < score.length-1; i++) {
int rank = 5;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
// 3. 결과
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
==== 성적처리 표 만들기, 품질 2단계 (04) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++Score|
public class Score{
private String[][] score;
Score(String[][] score){
this.score = score;
}
void sum() {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum + "";
}
}
void avg() {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
void rank() {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
void total() {
int totalSum = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
void print() {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
Score s = new Score(score);
s.sum();
s.avg();
s.rank();
s.total();
// 3. 결과
s.print();
}
}
++++
==== 성적처리 표 만들기, 품질 3단계 (05) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++PScore|
public class PScore {
private String[][] score;
PScore(String[][] score){
this.score = score;
}
void sum() {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum + "";
}
}
void avg() {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
void rank() {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
void total() {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
void print() {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++Score|
public class Score extends PScore{
Score(String[][] score) {
super(score);
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
Score s = new Score(score);
s.sum();
s.avg();
s.rank();
s.total();
// 3. 결과
s.print();
}
}
++++
==== 성적처리 표 만들기, 품질 4단계 (06) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++PScore|
public abstract class PScore {
abstract void sum();
abstract void avg();
abstract void rank();
abstract void total();
abstract void print();
}
++++
++++PScore|
public class Score extends PScore{
private String[][] score;
Score(String[][] score) {
this.score = score;
}
public void sum() {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum + "";
}
}
public void avg() {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
public void rank() {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
public void total() {
int totalSum = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void print() {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
Score s = new Score(score);
s.sum();
s.avg();
s.rank();
s.total();
// 3. 결과
s.print();
}
}
++++
==== 성적처리 표 만들기, 품질 5단계 (07) ====
++++석차 표 만들기|
1. 입력
-----------------------------------------------
이름 C# Java HTML5
-----------------------------------------------
홍길동 90 80 70
강감찬 80 90 60
유관순 80 30 60
이순신 80 20 60
김갑순 70 90 60
-----------------------------------------------
2. 결과
----------------------------------------------------------
이름 C# Java HTML5 합 평균 석차
----------------------------------------------------------
홍길동 90 80 70 ? ?
강감찬 80 90 60 ? ?
유관순 80 30 60 ? ?
이순신 80 20 60 ? ?
김갑순 70 90 60 ? ?
----------------------------------------------------------
총점 ? ? ? ? -
----------------------------------------------------------
++++
++++IScore|
interface IScore {
void sum();
void avg();
void rank();
void total();
void print();
}
++++
++++Score|
public class Score implements IScore{
private String[][] score;
Score(String[][] score) {
this.score = score;
}
public void sum() {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum + "";
}
}
public void avg() {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
public void rank() {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
public void total() {
int totalSum = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void print() {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
Score s = new Score(score);
s.sum();
s.avg();
s.rank();
s.total();
// 3. 결과
s.print();
}
}
++++
==== UML 사용====
==== 품질 1단계 (계산기 프로젝트 02) ====
**Integer.pharseInt 사용**
++++ TestCal|
public class TestCal {
public static void main(String[] args) {
System.out.println(args[0]); //"5"
System.out.println(args[1]); //"add"
System.out.println(args[2]); //"3"
int op1 = Integer.parseInt(args[0]); //5
String op = args[1]; //add
int op2 = Integer.parseInt(args[2]); //3
if(op.equals("add")) {
System.out.print(op1 + op2);
} else if (op.equals("sub")) {
System.out.print(op1 - op2);
} else if (op.equals("mul")) {
System.out.print(op1 / op2);
} else if (op.equals("div")) {
System.out.print(op1 * op2);
}
}
}
++++
**결과 :**
8
==== 품질 2단계 (계산기 프로젝트 03) ====
**메서드 정의 사용하기**
++++TestCal|
public class TestCal {
public static void main(String[] args) {
Cal c = new Cal();
c.doCal(args);
c.getResult();
}
}
++++
++++Cal|
public class Cal {
private int result;
void doCal(String[] args) {
int op1 = Integer.parseInt(args[0]); // 5
String op = args[1]; // add
int op2 = Integer.parseInt(args[2]); // 3
if (op.equals("add")) {
result = op1 + op2;
} else if (op.equals("sub")) {
result = op1 - op2;
} else if (op.equals("mul")) {
result = op1 * op2;
} else if (op.equals("div")) {
result = op1 / op2;
}
}
void getResult() {
System.out.println(result);
}
}
++++
**결과 :**
8
==== 품질 3단계 (계산기 프로젝트 04) ====
**상속관계를 사용**
++++TestCal|
public class TestCal {
public static void main(String[] args) {
Cal c = new Cal();
c.doCal(args);
c.getResult();
}
}
++++
++++Cal|
public class Cal extends PCal{
}
++++
++++PCal|
public class PCal {
private int result;
void doCal(String[] args) {
int op1 = Integer.parseInt(args[0]); // 5
String op = args[1]; // add
int op2 = Integer.parseInt(args[2]); // 3
if (op.equals("add")) {
result = op1 + op2;
} else if (op.equals("sub")) {
result = op1 - op2;
} else if (op.equals("mul")) {
result = op1 * op2;
} else if (op.equals("div")) {
result = op1 / op2;
}
}
void getResult() {
System.out.println(result);
}
}
++++
**결과 :**
8
==== 품질 4단계 (계산기 프로젝트 05) ====
**상속 + 메서드 정의**
++++TestCal|
public class TestCal {
public static void main(String[] args) {
Cal c = new Cal();
c.doCal(args);
c.getResult();
}
}
++++
++++Cal|
public class Cal extends PCal{
private int result;
void doCal(String[] args) {
int op1 = Integer.parseInt(args[0]); // 5
String op = args[1]; // add
int op2 = Integer.parseInt(args[2]); // 3
if (op.equals("add")) {
result = op1 + op2;
} else if (op.equals("sub")) {
result = op1 - op2;
} else if (op.equals("mul")) {
result = op1 * op2;
} else if (op.equals("div")) {
result = op1 / op2;
}
}
void getResult() {
System.out.println(result);
}
++++
++++CalP|
abstract class CalP {
abstract void doCal(String[] args);
abstract void getResult();
}
++++
**결과 :**
8
==== 품질 5단계 (계산기 프로젝트 06) ====
**interface 의 사용**
++++TestCal|
public class TestCal {
public static void main(String[] args) {
CalImpl ic = new CalImpl();
ic.doCal(args);
ic.getResult();
}
}
++++
++++CalImpl|
public class CalImpl implements ICal{
private int result;
public void doCal(String[] args) {
int op1 = Integer.parseInt(args[0]); // 5
String op = args[1]; // add
int op2 = Integer.parseInt(args[2]); // 3
if (op.equals("add")) {
result = op1 + op2;
} else if (op.equals("sub")) {
result = op1 - op2;
} else if (op.equals("mul")) {
result = op1 * op2;
} else if (op.equals("div")) {
result = op1 / op2;
}
}
public void getResult() {
System.out.println(result);
}
}
++++
++++ICal|
interface ICal {
void doCal(String[] args);
void getResult();
}
++++
**결과 :**
8
====품질 1단계 - 실행클래스, (FooBarBaz 03) ====
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
==== 품질 2단계 - 헬퍼클래스, (FooBarBaz 04) ====
++++FooBarBaz|
public class FooBarBaz {
void printFooBarBaz() {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBaz fz = new FooBarBaz();
fz.printFooBarBaz();
}
}
++++
==== 품질 3단계 - 단순클래스 상속, (FooBarBaz 05) ====
++++PFooBarBaz|
public class PFooBarBaz {
void printFooBarBaz() {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
++++FooBarBaz|
public class FooBarBaz extends PFooBarBaz {
}
++++
++++TestFooBarBaz|
public abstract class TestFooBarBaz {
public static void main(String[] args) {
FooBarBaz fz = new FooBarBaz();
fz.printFooBarBaz();
}
}
++++
==== 품질 4단계 - 추상클래스 상속, (FooBarBaz 06) ====
++++FooBarBaz|
public class FooBarBaz extends PFooBarBaz {
@Override
void printFooBarBaz() {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
++++PFooBarBa|
public abstract class PFooBarBaz {
abstract void printFooBarBaz();
}
++++
++++TestFooBarBaz|
public abstract class TestFooBarBaz {
public static void main(String[] args) {
FooBarBaz fz = new FooBarBaz();
fz.printFooBarBaz();
}
}
++++
==== 품질 5단계 - 인터페이스 구현 상속, (FooBarBaz 07) ====
++++IFooBarBaz|
interface IFooBarBaz {
void printFooBarBaz();
}
++++
++++FooBarBazImpl|
public class FooBarBazImpl implements IFooBarBaz {
@Override
public void printFooBarBaz() {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
++++TestFooBarBaz|
public abstract class TestFooBarBaz {
public static void main(String[] args) {
IFooBarBaz fz = new FooBarBazImpl();
fz.printFooBarBaz();
}
}
++++
==== 품질 6단계 (계산기 프로젝트 07) ====
**Loose Abstract Coupling**
++++ICal|
interface ICal {
public void calc();
public void printResult();
}
++++
++++CalImpl|
public class CalImpl implements ICal {
private String[] args;
private int op1;
private String op;
private int op2;
private int result;
CalImpl(String[] args){
this.args = args;
}
public void calc() {
this.op1 = Integer.parseInt(args[0]);
this.op = args[1];
this.op2 = Integer.parseInt(args[2]);
if(op.equals("add")) {
result = op1 + op2;
} else if(op.equals("sub")) {
result = op1 - op2;
} else if(op.equals("mul")) {
result = op1 * op2;
} else if(op.equals("div")) {
result = op1 / op2;
}
}
public void printResult() {
System.out.println(result);
}
}
++++
++++Cal|
public class Cal {
ICal ic;
Cal(String[] args){
ic = new CalImpl(args);
}
void calc() {
ic.calc();
}
void printResult() {
ic.printResult();
}
}
++++
++++TestCal|
public class TestCal {
public static void main(String[] args) {
// 입력
// 처리
Cal c = new Cal(args);
c.calc();
// 출력
c.printResult();
}
}
++++
==== 성적처리 표 만들기, 품질 6단계 (08) ====
++++IScore|
interface IScore {
void doService();
void print();
}
++++
++++ScoreImpl|
public class ScoreImpl implements IScore{
private String[][] score;
public ScoreImpl(String[][] score) {
this.score = score;
}
public void sum() {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum + "";
}
}
public void avg() {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
public void rank() {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
public void total() {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void doService() {
sum();
avg();
rank();
total();
}
public void print() {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++Score|
public class Score {
IScore is;
Score(String[][] score){
is = new ScoreImpl(score);
}
void doService() {
is.doService();
}
void print() {
is.print();
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
Score s = new Score(score);
s.doService();
// 3. 결과
s.print();
}
}
++++
==== 품질 6단계(FooBarBaz 03) ====
++++IFooBarBaz|
interface IFooBarBaz {
void printFooBarBaz();
}
++++
++++FooBarBazImpl|
public class FooBarBazImpl implements IFooBarBaz {
@Override
public void printFooBarBaz() {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(" foo");
}
if(i % 5 == 0) {
System.out.printf(" bar");
}
if(i % 7 == 0) {
System.out.printf(" baz");
}
System.out.printf("\n");
}
System.out.printf("\nand so on.");
}
}
++++
++++FooBarBaz|
public class FooBarBaz {
IFooBarBaz fb;
FooBarBaz(){
fb = new FooBarBazImpl();
}
void printFooBarBaz() {
fb.printFooBarBaz();
}
}
++++
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBaz fb = new FooBarBaz();
fb.printFooBarBaz();
}
}
++++
==== 공학계산기 - 품질 1단계 ====
++++|
++++
==== 엘레베이터 프로젝트 01 ====
++++예제|
public class Elevator {
public boolean doorOpen=false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door.");
doorOpen = true;
System.out.println("Door is open.");
}
public void closeDoor() {
System.out.println("Closing door.");
doorOpen = false;
System.out.println("Door is closed.");
}
public void goUp() {
System.out.println("Going up one floor.");
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
public void goDown() {
System.out.println("Going down one floor.");
currentFloor--;
System.out.println("Floor: " + currentFloor);
}
}
++++
++++Elevator|
public class Elevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
public void goDown() {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
++++
++++ElevatorTest|
public class ElevatorTest{
public static void main(String[] args) {
Elevator myElevator = new Elevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 02 ====
++++예제|
public class IfElevator {
public boolean doorOpen=false; // Doors are closed by default
public int currentFloor = 1; // All elevators start on first floor
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door.");
doorOpen = true;
System.out.println("Door is open.");
}
public void closeDoor() {
System.out.println("Closing door.");
doorOpen = false;
System.out.println("Door is closed.");
}
public void goUp() {
System.out.println("Going up one floor.");
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
public void goDown() {
if (currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
}
if (currentFloor > MIN_FLOORS) {
System.out.println("Going down one floor.");
currentFloor--;
System.out.println("Floor: " + currentFloor);
}
}
}
public class IfElevatorTest {
public static void main(String args[]) {
IfElevator myIfElevator = new IfElevator();
myIfElevator.openDoor();
myIfElevator.closeDoor();
myIfElevator.goDown();
myIfElevator.goUp();
myIfElevator.goUp();
myIfElevator.goUp();
myIfElevator.openDoor();
myIfElevator.closeDoor();
myIfElevator.goDown();
myIfElevator.openDoor();
myIfElevator.closeDoor();
myIfElevator.goDown();
myIfElevator.openDoor();
}
}
++++
++++IfElevator|
public class IfElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
}
if(currentFloor < TOP_FLOOR) {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
}
if(currentFloor > MIN_FLOORS) {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
}
++++
++++IfElevatorTest|
public class IfElevatorTest{
public static void main(String[] args) {
IfElevator myElevator = new IfElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 03 ====
++++예제|
public class NestedIfElevator {
public boolean doorOpen=false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door.");
doorOpen = true;
System.out.println("Door is open.");
}
public void closeDoor() {
System.out.println("Closing door.");
doorOpen = false;
System.out.println("Door is closed.");
}
public void goUp() {
System.out.println("Going up one floor.");
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
public void goDown() {
if (currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
}
if (currentFloor > MIN_FLOORS) {
if (!doorOpen) {
System.out.println("Going down one floor.");
currentFloor--;
System.out.println("Floor: " + currentFloor);
}
}
}
}
public class NestedIfElevatorTest {
public static void main(String args[]) {
NestedIfElevator myNestedIfElevator = new NestedIfElevator();
myNestedIfElevator.openDoor();
myNestedIfElevator.closeDoor();
myNestedIfElevator.goDown();
myNestedIfElevator.goUp();
myNestedIfElevator.goUp();
myNestedIfElevator.goUp();
myNestedIfElevator.openDoor();
myNestedIfElevator.closeDoor();
myNestedIfElevator.goDown();
myNestedIfElevator.openDoor();
myNestedIfElevator.closeDoor();
myNestedIfElevator.goDown();
myNestedIfElevator.openDoor();
}
}
++++
++++NestedIfElevator|
public class NestedIfElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
}
if(currentFloor < TOP_FLOOR) {
if(!doorOpen) {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
}
if(currentFloor > MIN_FLOORS) {
if(!doorOpen) {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
}
}
++++
++++NestedIfElevatorTest{|
public class NestedIfElevatorTest{
public static void main(String[] args) {
NestedIfElevator myElevator = new NestedIfElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 04 ====
++++예제|
public class IfElseElevator {
public boolean doorOpen=false; // Doors are closed by default
public int currentFloor = 1; // All elevators start on first floor
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door.");
doorOpen = true;
System.out.println("Door is open.");
}
public void closeDoor() {
System.out.println("Closing door.");
doorOpen = false;
System.out.println("Door is closed.");
}
public void goUp() {
System.out.println("Going up one floor.");
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
public void goDown() {
if (currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor.");
currentFloor--;
System.out.println("Floor: " + currentFloor);
}
}
}
public class IfElseElevatorTest {
public static void main(String args[]) {
IfElseElevator myIfElseElevator = new IfElseElevator();
myIfElseElevator.openDoor();
myIfElseElevator.closeDoor();
myIfElseElevator.goDown();
myIfElseElevator.goUp();
myIfElseElevator.goUp();
myIfElseElevator.goUp();
myIfElseElevator.openDoor();
myIfElseElevator.closeDoor();
myIfElseElevator.goDown();
myIfElseElevator.openDoor();
myIfElseElevator.closeDoor();
myIfElseElevator.goDown();
myIfElseElevator.openDoor();
}
}
++++
++++IfElseElevator|
public class IfElseElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
}
++++
++++IfElseElevatorTest|
public class IfElseElevatorTest{
public static void main(String[] args) {
IfElseElevator myElevator = new IfElseElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 05====
++++예제|
public class WhileElevator {
public boolean doorOpen=false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10
public final int BOTTOM_FLOOR = 1;
public void openDoor() {
System.out.println("Opening door.");
doorOpen = true;
System.out.println("Door is open.");
}
public void closeDoor() {
System.out.println("Closing door.");
doorOpen = false;
System.out.println("Door is closed.");
}
public void goUp() {
System.out.println("Going up one floor.");
currentFloor++;
System.out.println("Floor: " + currentFloor);
}
public void goDown() {
System.out.println("Going down one floor.");
currentFloor--;
System.out.println("Floor: " + currentFloor);
}
public void setFloor() {
int desiredFloor = 5;
while (currentFloor != desiredFloor){
if (currentFloor < desiredFloor) {
goUp();
}
else {
goDown();
}
}
}
}
public class WhileElevatorTest {
public static void main(String args[]) {
WhileElevator myElevator = new WhileElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.setFloor();
myElevator.openDoor();
}
}
++++
++++WhileElevator|
public class WhileElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
public void setFloor() {
int desiredFloor = 5;
while(currentFloor != desiredFloor) {
if(currentFloor < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++WhileElevatorTest|
public class WhileElevatorTest{
public static void main(String[] args) {
WhileElevator myElevator = new WhileElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 06 ====
do ~while문을 활용해서 Refactoring
++++DoWhileElevator|
public class DoWhileElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
public void setFloor() {
int desiredFloor = 5;
do {
if(currentFloor < desiredFloor) {
goUp();
} else {
goDown();
}
}while(currentFloor != desiredFloor);
}
}
++++
++++DoWhileElevatorTest|
public class DoWhileElevatorTest{
public static void main(String[] args) {
DoWhileElevator myElevator = new DoWhileElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor();
myElevator.openDoor();
}
}
++++
==== 엘레베이터 프로젝트 07 ====
엘레베이터 프로젝트 05 , 06 리펙토링
++++예제|
TestForElevator.class
public class TestForElevator {
public static void main(String[] args) {
ForElevator myElevator = new ForElevator();
int desiredFloor = Integer.parseInt(args[0]);
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor(desiredFloor);
myElevator.openDoor();
}
}
ForElevator.class
public class ForElevator {
private boolean doorOpen = false;
private int currentFloor = 1;
private final int TOP_FLOOR = 10;
private final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
public void setFloor(int desiredFloor) {
for(;currentFloor != desiredFloor;) {
if(currentFloor < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++ForElevator|
public class ForElevator {
public boolean doorOpen = false;
public int currentFloor = 1;
public final int TOP_FLOOR = 10;
public final int MIN_FLOORS = 1;
public void openDoor() {
System.out.println("Opening door");
doorOpen = true;
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
doorOpen = false;
System.out.println("Door is closed");
}
public void goUp() {
if(currentFloor == TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
currentFloor++;
System.out.println("Floor: "+currentFloor);
}
}
public void goDown() {
if(currentFloor == MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
currentFloor--;
System.out.println("Floor: "+currentFloor);
}
}
public void setFloor() {
int desiredFloor = 5;
for(;currentFloor != desiredFloor;) {
if(currentFloor < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++ForElevatorTest|
public class ForElevatorTest{
public static void main(String[] args) {
ForElevator myElevator = new ForElevator();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor();
myElevator.openDoor();
}
}
++++
==== 객체카운터 프로젝트 - 품질 1단계 ====
문제 : 객체를 생성할 때마다 카운트를 하여, 총 몇 개의 객체가 생성되었는지 출력하는 프로그램을 작성하시오.
++++TestCounter|
public class TestCounter {
private static int count;
TestCounter() {
count++;
}
public static int getCount() {
return count;
}
public static void main(String[] args) {
TestCounter tc1 = new TestCounter();
TestCounter tc2 = new TestCounter();
TestCounter tc3 = new TestCounter();
TestCounter tc4 = new TestCounter();
System.out.println(TestCounter.getCount());
}
}
++++
==== 객체카운터 프로젝트 - 품질 2단계 ====
문제 : 객체를 생성할 때마다 카운트를 하여, 총 몇 개의 객체가 생성되었는지 출력하는 프로그램을 작성하시오.
++++예제|
Counter.class
public class Counter {
private static int count;
public Counter() {
count++;
}
public static int getCount() {
return count;
}
}
TestCounter.class
public class TestCounter {
public static void main(String[] args) {
Counter counter1 = new Counter();
Counter counter2 = new Counter();
Counter counter3 = new Counter();
System.out.println(Counter.getCount());
}
}
++++
++++Counter|
public class Counter {
private static int count;
Counter(){
count++;
}
public static int getCount() {
return count;
}
}
++++
++++TestCounter|
public class TestCounter {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
Counter c4 = new Counter();
System.out.println(Counter.getCount());
}
}
++++
==== 객체카운터 프로젝트 - 품질 3단계 ====
++++PCounter|
public class PCounter {
private static int count;
PCounter(){
count++;
}
public static int getCount() {
return count;
}
}
++++
++++Counter|
public class Counter extends PCounter {
}
++++
++++TestCounter|
public class TestCounter {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
Counter c4 = new Counter();
System.out.println(Counter.getCount());
}
}
++++
==== 객체카운터 프로젝트 - 품질 4단계 ====
++++PCounter|
public abstract class PCounter {
}
++++
++++Counter |
public class Counter extends PCounter {
private static int count;
Counter(){
count++;
}
public static int getCount() {
return count;
}
}
++++
++++TestCounter |
public class TestCounter {
public static void main(String[] args) {
PCounter c1 = new Counter();
PCounter c2 = new Counter();
PCounter c3 = new Counter();
PCounter c4 = new Counter();
System.out.println(Counter.getCount());
}
}
++++
==== 객체카운터 프로젝트 - 품질 5단계 ====
++++ICounter|
interface ICounter {
}
++++
++++Counterimpl|
public class Counterimpl implements ICounter {
private static int count;
Counterimpl(){
count++;
}
public static int getCount() {
return count;
}
}
++++
++++|
++++
++++TestCounter |
public class TestCounter {
public static void main(String[] args) {
ICounter c1 = new Counterimpl();
ICounter c2 = new Counterimpl();
ICounter c3 = new Counterimpl();
ICounter c4 = new Counterimpl();
System.out.println(Counterimpl.getCount());
}
}
++++
==== 객체카운터 프로젝트 - 품질 6단계 ====
++++ICounter |
interface ICounter {
}
++++
++++CounterImpl|
public class CounterImpl implements ICounter {
private static int count;
CounterImpl(){
count++;
}
public static int getCount() {
return count;
}
}
++++
++++Counter|
public class Counter {
private ICounter ci;
Counter(){
ci = new CounterImpl();
}
public static int getCount() {
return CounterImpl.getCount();
}
}
++++
++++TestCounter |
public class TestCounter {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();
Counter c4 = new Counter();
System.out.println(Counter.getCount());
}
}
++++
==== 가위바위보 프로젝트 - 품질 1단계 ====
{{ :programmer:image.png?600 |}}
++++TestWinner|
public class TestWinner {
public static void main(String[] args) {
int aWin = 0;
int bWin = 0;
int tie = 0;
int T = 10000;
// 가위 = 1, 바위 = 2, 보 = 3
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
System.out.println("10000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("10000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("10000번 중 비긴 경기 : "+tie);
}
}
++++
==== 가위바위보 프로젝트 - 품질 2단계 ====
++++Rsp|
public class Rsp {
private int aWin = 0;
private int bWin = 0;
private int tie = 0;
private int T = 10000;
public void playRsp() {
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
// 가위 : 1, 바위 : 2, 보 : 3
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
}
public void printResult() {
System.out.println("1000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("1000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("1000번 중 비긴 경기 : "+tie);
}
}
++++
++++TestRsp|
public class TestRsp {
public static void main(String[] args) {
Rsp r = new Rsp();
r.playRsp();
r.printResult();
}
}
++++
==== 가위바위보 프로젝트 - 품질 3단계 ====
++++PRsp|
public class PRsp {
private int aWin = 0;
private int bWin = 0;
private int tie = 0;
private int T = 10000;
public void playRsp() {
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
// 가위 : 1, 바위 : 2, 보 : 3
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
}
public void printResult() {
System.out.println("1000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("1000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("1000번 중 비긴 경기 : "+tie);
}
}
++++
++++Rsp|
public class Rsp extends PRsp{
}
++++
++++TestRsp|
public class TestRsp {
public static void main(String[] args) {
Rsp r = new Rsp();
r.playRsp();
r.printResult();
}
}
++++
==== 가위바위보 프로젝트 - 품질 4단계 ====
++++PRsp|
public abstract class PRsp {
public abstract void playRsp();
public abstract void printResult();
}
++++
++++Rsp|
public class Rsp extends PRsp{
private int aWin = 0;
private int bWin = 0;
private int tie = 0;
private int T = 10000;
public void playRsp() {
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
// 가위 : 1, 바위 : 2, 보 : 3
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
}
public void printResult() {
System.out.println("1000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("1000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("1000번 중 비긴 경기 : "+tie);
}
}
++++
++++TestRsp|
public class TestRsp {
public static void main(String[] args) {
Rsp r = new Rsp();
r.playRsp();
r.printResult();
}
}
++++
==== 가위바위보 프로젝트 - 품질 5단계 ====
++++IRsp|
interface IRsp {
void playRsp();
void printResult();
}
++++
++++RspImpl|
public class Rspimpl implements IRsp{
private int aWin = 0;
private int bWin = 0;
private int tie = 0;
private int T = 10000;
public void playRsp() {
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
// 가위 : 1, 바위 : 2, 보 : 3
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
}
public void printResult() {
System.out.println("1000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("1000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("1000번 중 비긴 경기 : "+tie);
}
}
++++
++++TestRsp|
public class TestRsp {
public static void main(String[] args) {
IRsp r = new RspImpl();
r.playRsp();
r.printResult();
}
}
++++
==== 가위바위보 프로젝트 - 품질 6단계 ====
++++IRsp|
interface IRsp {
void playRsp();
void printResult();
}
++++
++++Rspimpl|
public class Rspimpl implements IRsp{
private int aWin = 0;
private int bWin = 0;
private int tie = 0;
private int T = 10000;
public void playRsp() {
while(T > 0) {
int rA = (int)(Math.random()*3)+1;
int rB = (int)(Math.random()*3)+1;
// 가위 : 1, 바위 : 2, 보 : 3
final String robotA = (rA == 1) ? "가위" : (rA == 2) ? "바위" : "보";
final String robotB = (rB == 1) ? "가위" : (rB == 2) ? "바위" : "보";
if(robotA.equals(robotB)) {
tie++;
} else {
if(robotA.equals("가위")) {
if(robotB.equals("바위")) {
bWin++;
} else { // robotB.equals("보")
aWin++;
}
} else if(robotA.equals("바위")) {
if(robotB.equals("가위")) {
aWin++;
} else { // robotB.equals("보")
bWin++;
}
} else { // robotA.equals("보")
if(robotB.equals("가위")) {
bWin++;
} else { // robotB.equals("바위")
aWin++;
}
}
}
T--;
}
}
public void printResult() {
System.out.println("1000번 중 컴퓨터A의 승리 : "+aWin);
System.out.println("1000번 중 컴퓨터B의 승리 : "+bWin);
System.out.println("1000번 중 비긴 경기 : "+tie);
}
}
++++
++++Rsp|
public class Rsp {
IRsp ir;
Rsp(){
ir = new Rspimpl();
}
public void playRsp() {
ir.playRsp();
}
public void printResult() {
ir.printResult();
}
}
++++
++++TestRsp|
public class TestRsp {
public static void main(String[] args) {
Rsp r = new Rsp();
r.playRsp();
r.printResult();
}
}
++++
==== 계산기 프로젝트 - 품질 7단계 ====
++++ICal |
interface ICal {
public void calc(CalVO vo);
public void printResult(CalVO vo);
}
++++
++++CalImpl |
public class CalImpl implements ICal {
private int op1;
private String op;
private int op2;
public void calc(CalVO vo) {
this.op1 = Integer.parseInt(vo.getOp1());
this.op = vo.getOp();
this.op2 = Integer.parseInt(vo.getOp2());
if(op.equals("add")) {
vo.setResult(op1 + op2);
} else if(op.equals("sub")) {
vo.setResult(op1 - op2);
} else if(op.equals("mul")) {
vo.setResult(op1 * op2);
} else if(op.equals("div")) {
vo.setResult(op1 / op2);
}
}
public void printResult(CalVO vo) {
System.out.println(vo.getResult());
}
}
++++
++++CalVO |
public class CalVO {
private String op1;
private String op;
private String op2;
private int result;
CalVO(String[] args) {
this.op1 = args[0];
this.op = args[1];
this.op2 = args[2];
}
public String getOp1() {
return op1;
}
public void setOp1(String op1) {
this.op1 = op1;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String getOp2() {
return op2;
}
public void setOp2(String op2) {
this.op2 = op2;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
++++
++++Cal|
public class Cal {
ICal ic;
Cal(){
ic = new CalImpl();
}
void calc(CalVO vo) {
ic.calc(vo);
}
void printResult(CalVO vo) {
ic.printResult(vo);
}
}
++++
++++TestCal |
public class TestCal {
public static void main(String[] args) {
// 입력
// 처리
CalVO vo = new CalVO(args);
Cal c = new Cal();
c.calc(vo);
// 출력
c.printResult(vo);
}
}
++++
==== 성적처리 표 만들기, 품질 7단계 (09) ====
++++IScore |
interface IScore {
void doService();
void print();
}
++++
++++ScoreImpl|
public class ScoreImpl implements IScore{
private ScoreVO vo;
ScoreImpl(ScoreVO vo){
this.vo = vo;
}
public void doService() {
String[][] score = vo.getScore();
sum(score);
avg(score);
rank(score);
total(score);
}
private void sum(String[][] score) {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum+"";
}
}
private void avg(String[][] score) {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
private void rank(String[][] score) {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
private void total(String[][] score) {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void print() {
String[][] score = vo.getScore();
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++ScoreVO |
public class ScoreVO {
private String[][] score;
ScoreVO(String[][] score){
this.score = score;
}
public String[][] getScore() {
return score;
}
public void setScore(String[][] score) {
this.score = score;
}
}
++++
++++Score|
public class Score {
IScore is;
Score(ScoreVO vo){
is = new ScoreImpl(vo);
}
void doService() {
is.doService();
}
void print() {
is.print();
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
ScoreVO vo = new ScoreVO(score);
Score s = new Score(vo);
s.doService();
// 3. 결과
s.print();
}
}
++++
==== 품질 7단계(FooBarBaz 04) ====
++++IFooBarBaz|
interface IFooBarBaz {
void printFooBarBaz(FooBarBazVO vo);
}
++++
++++FooBarBazImpl|
public class FooBarBazImpl implements IFooBarBaz {
@Override
public void printFooBarBaz(FooBarBazVO vo) {
for(int i = 1; i <= 16; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(vo.getFoo());
}
if(i % 5 == 0) {
System.out.printf(vo.getBar());
}
if(i % 7 == 0) {
System.out.printf(vo.getBaz());
}
System.out.println();
}
System.out.println();
System.out.print(vo.getAndSoOn());
}
}
++++
++++FooBarBazVO |
public class FooBarBazVO {
private String foo;
private String bar;
private String baz;
private String andSoOn;
FooBarBazVO(String foo, String bar, String baz, String andSoOn) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.andSoOn = andSoOn;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
public String getBaz() {
return baz;
}
public void setBaz(String baz) {
this.baz = baz;
}
public String getAndSoOn() {
return andSoOn;
}
public void setAndSoOn(String andSoOn) {
this.andSoOn = andSoOn;
}
}
++++
++++FooBarBaz |
public class FooBarBaz {
IFooBarBaz fb;
FooBarBaz(){
fb = new FooBarBazImpl();
}
void printFooBarBaz(FooBarBazVO vo) {
fb.printFooBarBaz(vo);
}
}
++++
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBazVO vo = new FooBarBazVO(" foo", " bar", " baz", "and so on.");
FooBarBaz fb = new FooBarBaz();
fb.printFooBarBaz(vo);
}
}
++++
==== 엘레베이터 프로젝트 - 품질 7단계 (08) ====
++++IElevator|
interface IElevator {
public void openDoor();
public void closeDoor();
public void goUp();
public void goDown();
public void setFloor(int desiredFloor);
}
++++
++++ElevatorImpl |
public class ElevatorImpl implements IElevator {
private ElevatorVO vo;
ElevatorImpl(ElevatorVO vo){
this.vo = vo;
}
public void openDoor() {
System.out.println("Opening door");
vo.setDoorOpen(true);
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
vo.setDoorOpen(false);
System.out.println("Door is closed");
}
public void goUp() {
if(vo.getCurrentFloor() == vo.getTOP_FLOOR()) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
vo.setCurrentFloor(vo.getCurrentFloor()+1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void goDown() {
if(vo.getCurrentFloor() == vo.getMIN_FLOORS()) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
vo.setCurrentFloor(vo.getCurrentFloor()-1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void setFloor(int desiredFloor) {
while(vo.getCurrentFloor() != desiredFloor) {
if(vo.getCurrentFloor() < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++ElevatorVO|
public class ElevatorVO {
private boolean doorOpen;
private int currentFloor;
private final int TOP_FLOOR;
private final int MIN_FLOORS;
ElevatorVO(boolean doorOpen, int currentFloor, int TOP_FLOOR, int MIN_FLOORS) {
this.doorOpen = doorOpen;
this.currentFloor = currentFloor;
this.TOP_FLOOR = TOP_FLOOR;
this.MIN_FLOORS = MIN_FLOORS;
}
public boolean isDoorOpen() {
return doorOpen;
}
public void setDoorOpen(boolean doorOpen) {
this.doorOpen = doorOpen;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
public int getTOP_FLOOR() {
return TOP_FLOOR;
}
public int getMIN_FLOORS() {
return MIN_FLOORS;
}
}
++++
++++Elevator|
public class Elevator {
private IElevator ie;
Elevator(ElevatorVO vo){
ie = new ElevatorImpl(vo);
}
public void openDoor() {
ie.openDoor();
}
public void closeDoor() {
ie.closeDoor();
}
public void goUp() {
ie.goUp();
}
public void goDown() {
ie.goDown();
}
public void setFloor(int desiredFloor) {
ie.setFloor(desiredFloor);
}
}
++++
++++ElevatorTest|
public class ElevatorTest{
public static void main(String[] args) {
ElevatorVO vo = new ElevatorVO(false, 1, 10, 1); // doorOpen, currentFloor, TOP_FLOOR, MIN_FLOORS
Elevator myElevator = new Elevator(vo);
int desiredFloor = Integer.parseInt(args[0]);
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor(desiredFloor);
myElevator.openDoor();
}
}
++++
==== 품질 7단계 (계산기 프로젝트 08) ====
++++ICal |
interface ICal {
public void doService();
}
++++
++++CalImpl |
public class CalImpl implements ICal {
private CalVO vo;
CalImpl(CalVO vo){
this.vo = vo;
}
private void calc() throws NumberFormatException, ArithmeticException {
int op1 = Integer.parseInt(vo.getOp1());
String op = vo.getOp();
int op2 = Integer.parseInt(vo.getOp2());
if(op.equals("add")) {
vo.setResult(op1 + op2);
} else if(op.equals("sub")) {
vo.setResult(op1 - op2);
} else if(op.equals("mul")) {
vo.setResult(op1 * op2);
} else if(op.equals("div")) {
vo.setResult(op1 / op2);
}
}
private void printResult() {
System.out.println(vo.getResult());
}
@Override
public void doService() throws NumberFormatException, ArithmeticException {
calc();
printResult();
}
}
++++
++++CalVO|
public class CalVO {
private String op1;
private String op;
private String op2;
private int result;
CalVO(String[] args) {
try {
this.op1 = args[0];
this.op = args[1];
this.op2 = args[2];
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException!");
}
}
public String getOp1() {
return op1;
}
public void setOp1(String op1) {
this.op1 = op1;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String getOp2() {
return op2;
}
public void setOp2(String op2) {
this.op2 = op2;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
++++
++++Cal|
public class Cal {
private ICal ic;
Cal(CalVO vo){
ic = new CalImpl(vo);
}
void doService() {
try {
ic.doService();
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
} catch(ArithmeticException e) {
System.out.println("ArithmeticException!!");
} catch(Exception e) {
System.out.println("Exception!!");
}
}
}
++++
++++TestCal|
public class TestCal {
public static void main(String[] args) {
// 입력
// 처리
CalVO vo = new CalVO(args);
Cal c = new Cal(vo);
// 출력
c.doService();
}
}
++++
==== 성적처리 표 만들기, 품질 8단계 (09) ====
**예외처리, Built-In**
++++IScore|
interface IScore {
void doService();
void print();
}
++++
++++ScoreImpl|
public class ScoreImpl implements IScore{
private ScoreVO vo;
ScoreImpl(ScoreVO vo){
this.vo = vo;
}
public void doService() throws ArrayIndexOutOfBoundsException, NumberFormatException {
String[][] score = vo.getScore();
sum(score);
avg(score);
rank(score);
total(score);
}
private void sum(String[][] score) {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum+"";
}
}
private void avg(String[][] score) {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
private void rank(String[][] score) {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
private void total(String[][] score) {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void print() throws ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException {
String[][] score = vo.getScore();
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++ScoreImpl|
public class ScoreImpl implements IScore{
private ScoreVO vo;
ScoreImpl(ScoreVO vo){
this.vo = vo;
}
public void doService() throws ArrayIndexOutOfBoundsException, NumberFormatException {
String[][] score = vo.getScore();
sum(score);
avg(score);
rank(score);
total(score);
}
private void sum(String[][] score) {
int sum = 0;
for(int i = 0; i < score.length-1; i++) {
sum = Integer.parseInt(score[i][1]) + Integer.parseInt(score[i][2]) + Integer.parseInt(score[i][3]);
score[i][4] = sum+"";
}
}
private void avg(String[][] score) {
double avg = 0;
for(int i = 0; i < score.length-1; i++) {
avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
private void rank(String[][] score) {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
private void total(String[][] score) {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
public void print() throws ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException {
String[][] score = vo.getScore();
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++ScoreVO|
public class ScoreVO {
private String[][] score;
ScoreVO(String[][] score){
this.score = score;
}
public String[][] getScore() {
return score;
}
public void setScore(String[][] score) {
this.score = score;
}
}
++++
++++Score|
public class Score {
IScore is;
Score(ScoreVO vo){
is = new ScoreImpl(vo);
}
void doService() {
try {
is.doService();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException!!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
} catch(NullPointerException e) {
System.out.println("NullPointerException!!");
}
}
void print() {
try {
is.print();
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException!!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
} catch(NullPointerException e) {
System.out.println("NullPointerException!!");
}
}
}
++++
++++TestScore |
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
ScoreVO vo = new ScoreVO(score);
Score s = new Score(vo);
s.doService();
// 3. 결과
s.print();
}
}
++++
==== 엘레베이터 프로젝트 - 품질 8단계 (09) ====
++++IElevator |
interface IElevator {
public void openDoor();
public void closeDoor();
public void goUp();
public void goDown();
public void setFloor(String desiredFloor);
}
++++
++++ElevatorImpl |
public class ElevatorImpl implements IElevator {
private ElevatorVO vo;
ElevatorImpl(ElevatorVO vo){
this.vo = vo;
}
public void openDoor() {
System.out.println("Opening door");
vo.setDoorOpen(true);
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
vo.setDoorOpen(false);
System.out.println("Door is closed");
}
public void goUp() {
if(vo.getCurrentFloor() == vo.getTOP_FLOOR()) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
vo.setCurrentFloor(vo.getCurrentFloor()+1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void goDown() {
if(vo.getCurrentFloor() == vo.getMIN_FLOORS()) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
vo.setCurrentFloor(vo.getCurrentFloor()-1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void setFloor(String PdesiredFloor) throws ArrayIndexOutOfBoundsException, NumberFormatException {
int desiredFloor = Integer.parseInt(PdesiredFloor);
while(vo.getCurrentFloor() != desiredFloor) {
if(vo.getCurrentFloor() < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++ElevatorVO |
public class ElevatorVO {
private final int TOP_FLOOR = 10;
private final int MIN_FLOORS = 1;
private int currentFloor = 1;
private boolean doorOpen = false;
public boolean isDoorOpen() {
return doorOpen;
}
public void setDoorOpen(boolean doorOpen) {
this.doorOpen = doorOpen;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
public int getTOP_FLOOR() {
return TOP_FLOOR;
}
public int getMIN_FLOORS() {
return MIN_FLOORS;
}
}
++++
++++Elevator|
public class Elevator {
private IElevator ie;
Elevator(ElevatorVO vo){
ie = new ElevatorImpl(vo);
}
public void openDoor() {
ie.openDoor();
}
public void closeDoor() {
ie.closeDoor();
}
public void goUp() {
ie.goUp();
}
public void goDown() {
ie.goDown();
}
public void setFloor(String desiredFloor) {
try {
ie.setFloor(desiredFloor);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException !!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException !!");
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생 !!");
}
}
}
++++
++++ElevatorTest|
public class ElevatorTest{
public static void main(String[] args) {
ElevatorVO vo = new ElevatorVO();
Elevator myElevator = new Elevator(vo);
String desiredFloor = args[0];
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor(desiredFloor);
myElevator.openDoor();
}
}
++++
==== 품질 8단계(FooBarBaz 04) ====
예외처리, Built-in
++++IFooBarBaz |
interface IFooBarBaz {
void printFooBarBaz(FooBarBazVO vo);
}
++++
++++FooBarBazImpl |
public class FooBarBazImpl implements IFooBarBaz {
@Override
public void printFooBarBaz(FooBarBazVO vo) throws NumberFormatException {
int start = Integer.parseInt(vo.getStart());
int end = Integer.parseInt(vo.getEnd());
for(int i = start; i <= end; i++) {
System.out.printf("%2d", i);
if(i % 3 == 0) {
System.out.printf(vo.getFoo());
}
if(i % 5 == 0) {
System.out.printf(vo.getBar());
}
if(i % 7 == 0) {
System.out.printf(vo.getBaz());
}
System.out.println();
}
System.out.println();
System.out.print(vo.getAndSoOn());
}
}
++++
++++FooBarBazVO|
public class FooBarBazVO {
private String foo;
private String bar;
private String baz;
private String andSoOn;
private String start;
private String end;
FooBarBazVO(String foo, String bar, String baz, String andSoOn) {
this.foo = foo;
this.bar = bar;
this.baz = baz;
this.andSoOn = andSoOn;
}
public String getFoo() {
return foo;
}
public void setFoo(String foo) {
this.foo = foo;
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
public String getBaz() {
return baz;
}
public void setBaz(String baz) {
this.baz = baz;
}
public String getAndSoOn() {
return andSoOn;
}
public void setAndSoOn(String andSoOn) {
this.andSoOn = andSoOn;
}
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
}
++++
++++FooBarBaz|
public class FooBarBaz {
private IFooBarBaz fb;
FooBarBaz(){
fb = new FooBarBazImpl();
}
void printFooBarBaz(FooBarBazVO vo) {
try {
fb.printFooBarBaz(vo);
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
}
}
}
++++
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBazVO vo = new FooBarBazVO(" foo", " bar", " baz", "and so on.");
vo.setStart("1");
vo.setEnd("16");
FooBarBaz fb = new FooBarBaz();
fb.printFooBarBaz(vo);
}
}
++++
==== 품질 9단계 (계산기 프로젝트 09) ====
예외처리, User-Defined
++++IScore|
interface IScore {
void doService() throws ArrayIndexOutOfBoundsException, NumberFormatException, ScoreSizeOutOfBoundException;
}
++++
++++ScoreImpl |
public class ScoreImpl implements IScore{
private ScoreVO vo;
ScoreImpl(ScoreVO vo){
this.vo = vo;
}
public void doService() throws ArrayIndexOutOfBoundsException, NumberFormatException, ScoreSizeOutOfBoundException {
String[][] score = vo.getScore();
sum(score);
avg(score);
rank(score);
total(score);
print(score);
}
private void sum(String[][] score) throws ScoreSizeOutOfBoundException {
for(int i = 0; i < score.length-1; i++) {
int num1 = Integer.parseInt(score[i][1]);
int num2 = Integer.parseInt(score[i][2]);
int num3 = Integer.parseInt(score[i][3]);
if(num1 < ScoreVO.MIN_SCORE || num2 < ScoreVO.MIN_SCORE || num3 < ScoreVO.MIN_SCORE) {
throw new ScoreSizeOutOfBoundException("가능한 점수 범위를 벗어난 값이 입력되었습니다.");
} else if(num1 > ScoreVO.MAX_SCORE || num2 > ScoreVO.MAX_SCORE || num3 > ScoreVO.MAX_SCORE) {
throw new ScoreSizeOutOfBoundException("가능한 점수 범위를 벗어난 값이 입력되었습니다.");
}
int sum = num1 + num2 + num3;
score[i][4] = sum+"";
}
}
private void avg(String[][] score) {
for(int i = 0; i < score.length-1; i++) {
double avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) /10d);
score[i][5] = avg+"";
}
}
private void rank(String[][] score) {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = rank+"";
}
}
private void total(String[][] score) {
int totalSum = 0;
int sum1 = 0, sum2 = 0, sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = sum1+"";
score[score.length-1][2] = sum2+"";
score[score.length-1][3] = sum3+"";
score[score.length-1][4] = totalSum+"";
}
private void print(String[][] score) throws ArrayIndexOutOfBoundsException, NumberFormatException, NullPointerException {
System.out.println("----------------------------------------------");
System.out.println(" 이름 C# JAVA HTML5 합 평균 석차");
System.out.println("----------------------------------------------");
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println("----------------------------------------------");}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++ScoreVO|
public class ScoreVO {
public final static int MAX_SCORE = 100;
public final static int MIN_SCORE = 0;
private String[][] score;
ScoreVO(String[][] score){
this.score = score;
}
public String[][] getScore() {
return score;
}
public void setScore(String[][] score) {
this.score = score;
}
}
++++
++++Score|
public class Score {
private IScore is;
Score(ScoreVO vo){
is = new ScoreImpl(vo);
}
void doService() {
try {
is.doService();
} catch(ScoreSizeOutOfBoundException e) {
System.out.println("ScoreSizeOutOfBoundException : "+e.getMessage());
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException!!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
} catch(NullPointerException e) {
System.out.println("NullPointerException!!");
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생!");
}
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
ScoreVO vo = new ScoreVO(score);
Score s = new Score(vo);
// 3. 결과
s.doService();
}
}
++++
++++User Defined Exception|
public class ScoreSizeOutOfBoundException extends Exception {
ScoreSizeOutOfBoundException(String msg){
super(msg);
}
}
++++
====엘리베이터 프로젝트 (J2SE, 품질9단계, 예외처리, User-Defined)====
성적처리 프로젝트 (J2SE, 품질9단계, 예외처리, User-Defined)
++++소스 'User-Defined Exception'|
1. Cannot Go up
class CannotGoUpException extends Exception {
CannotGoUpException(String msg) {
super(msg);
}
}
if(vo.getCurrentFloor() == vo.getTOP_FLOOR()) {
throw new CannotGoUpException("Cannot Go up");
}
2. Cannot Go down
class CannotGoDownException extends Exception {
CannotGoDownException(String msg) {
super(msg);
}
}
if(vo.getCurrentFloor() == vo.getMIN_FLOORS()) {
throw new CannotGoDownException("Cannot Go down");
}
++++
++++IElevator|
interface IElevator {
public void openDoor();
public void closeDoor();
public void goUp() throws CannotGoUpException;
public void goDown() throws CannotGoDownException;
public void setFloor(String desiredFloor) throws ArrayIndexOutOfBoundsException, NumberFormatException, CannotGoUpException, CannotGoDownException;
}
++++
++++ElevatorImpl|
public class ElevatorImpl implements IElevator {
private ElevatorVO vo;
ElevatorImpl(ElevatorVO vo){
this.vo = vo;
}
public void openDoor() {
System.out.println("Opening door");
vo.setDoorOpen(true);
System.out.println("Door is open");
}
public void closeDoor() {
System.out.println("Closing door");
vo.setDoorOpen(false);
System.out.println("Door is closed");
}
public void goUp() {
if(vo.getCurrentFloor() == ElevatorVO.TOP_FLOOR) {
System.out.println("Cannot Go up");
} else {
System.out.println("Going up one floor");
vo.setCurrentFloor(vo.getCurrentFloor()+1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void goDown() {
if(vo.getCurrentFloor() == ElevatorVO.MIN_FLOORS) {
System.out.println("Cannot Go down");
} else {
System.out.println("Going down one floor");
vo.setCurrentFloor(vo.getCurrentFloor()-1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
public void setFloor(String PdesiredFloor) throws NumberFormatException {
int desiredFloor = Integer.parseInt(PdesiredFloor);
while(vo.getCurrentFloor() != desiredFloor) {
if(vo.getCurrentFloor() < desiredFloor) {
goUp();
} else {
goDown();
}
}
}
}
++++
++++ElevatorVO|
public class ElevatorVO {
public final static int TOP_FLOOR = 10;
public final static int MIN_FLOORS = 1;
private int currentFloor = 1;
private boolean doorOpen = false;
public boolean isDoorOpen() {
return doorOpen;
}
public void setDoorOpen(boolean doorOpen) {
this.doorOpen = doorOpen;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
}
++++
++++Elevator|
public class Elevator {
private IElevator ie;
Elevator(ElevatorVO vo){
ie = new ElevatorImpl(vo);
}
public void openDoor() {
ie.openDoor();
}
public void closeDoor() {
ie.closeDoor();
}
public void goUp() {
try {
ie.goUp();
}catch(CannotGoUpException e) {
System.out.println("CannotGoUpException : "+e.getMessage());
}
}
public void goDown() {
try {
ie.goDown();
} catch(CannotGoDownException e) {
System.out.println("CannotGoDownException : "+e.getMessage());
}
}
public void setFloor(String desiredFloor) {
try {
ie.setFloor(desiredFloor);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException !!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException !!");
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생 !!");
}
}
}
++++
++++ElevatorTest|
public class ElevatorTest{
public static void main(String[] args) {
ElevatorVO vo = new ElevatorVO();
Elevator myElevator = new Elevator(vo);
String desiredFloor = args[0];
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goDown();
myElevator.openDoor();
myElevator.goDown();
myElevator.setFloor(desiredFloor);
myElevator.openDoor();
}
}
++++
++++User Defined Exception|
public class CannotGoDownException extends Exception {
CannotGoDownException(String msg){
super(msg);
}
}
public class CannotGoUpException extends Exception {
CannotGoUpException(String msg){
super(msg);
}
}
++++
====FooBarBaz 프로젝트 (J2SE, 품질9단계, 예외처리, User-Defined)====
++++소스|
class FooBarBazException extends Exception {
FooBarBazException(String msg) {
super(msg);
}
}
interface IFooBarBaz {
public void doFooBarBaz() throws FooBarBazException;
}
class FooBarBazImpl implements IFooBarBaz {
FooBarBazVO vo;
FooBarBazImpl(FooBarBazVO vo) {
this.vo = vo;
}
public void doFooBarBaz() throws FooBarBazException {
for(int i=1; i<110; i++) {
System.out.print(i);
if(i%3 == 0) {
System.out.print(" "+FooBarBazVO.FOO);
}
if(i%5 == 0) {
System.out.print(" "+FooBarBazVO.BAR);
}
if(i%7 == 0) {
System.out.print(" "+FooBarBazVO.BAZ);
}
if((i%3 == 0) && (i%5 == 0) && (i%7 == 0)) {
throw new FooBarBazException("\n\n축하합니다. "+FooBarBazVO.FOO_BAR_BAZ+" 입니다.");
}
System.out.println();
}
}
}
class FooBarBaz {
IFooBarBaz ifbb;
FooBarBaz(FooBarBazVO vo) {
ifbb = new FooBarBazImpl(vo);
}
void doFooBarBaz() {
try {
ifbb.doFooBarBaz();
} catch(FooBarBazException e) {
System.out.println(e.getMessage());
}
}
}
class FooBarBazVO {
final static String FOO = "Foo";
final static String BAR = "Bar";
final static String BAZ = "Baz";
final static String FOO_BAR_BAZ = "FooBarBaz";
}
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBazVO vo = new FooBarBazVO();
FooBarBaz fbb = new FooBarBaz(vo);
fbb.doFooBarBaz();
}
}
++++
++++IFooBarBaz|
interface IFooBarBaz {
void printFooBarBaz() throws FooBarBazException;
}
++++
++++FooBarBazImpl|
public class FooBarBazImpl implements IFooBarBaz {
FooBarBazVO vo;
FooBarBazImpl(FooBarBazVO vo){
this.vo = vo;
}
@Override
public void printFooBarBaz() throws FooBarBazException, NumberFormatException {
int start = Integer.parseInt(vo.getStart());
int end = Integer.parseInt(vo.getEnd());
for(int i = start; i < end; i++) {
System.out.print(i);
if(i % FooBarBazVO.THREE == 0) {
System.out.print(" "+FooBarBazVO.FOO);
}
if(i % FooBarBazVO.FIVE == 0) {
System.out.print(" "+FooBarBazVO.BAR);
}
if(i % FooBarBazVO.SEVEN == 0) {
System.out.print(" "+FooBarBazVO.BAZ);
}
System.out.println();
if((i % FooBarBazVO.THREE == 0) && (i % FooBarBazVO.FIVE == 0) && (i % FooBarBazVO.SEVEN == 0)) {
throw new FooBarBazException("축하합니다! "+ FooBarBazVO.FOO_BAR_BAZ +"입니다!");
}
}
System.out.println();
System.out.print("and so on.");
}
}
++++
++++FooBarBazVO|
public class FooBarBazVO {
public final static String FOO = "foo";
public final static String BAR = "bar";
public final static String BAZ = "baz";
public final static String FOO_BAR_BAZ = "foo bar baz";
public final static int THREE = 3;
public final static int FIVE = 5;
public final static int SEVEN = 7;
private String start;
private String end;
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
}
++++
++++FooBarBaz|
public class FooBarBaz {
IFooBarBaz fb;
FooBarBaz(FooBarBazVO vo){
fb = new FooBarBazImpl(vo);
}
void printFooBarBaz() {
try {
fb.printFooBarBaz();
} catch(FooBarBazException e) {
System.out.println("FooBarBazException : "+ e.getMessage());
} catch(NumberFormatException e) {
System.out.println("NumberFormatException! ");
}
}
}
++++
++++TestFooBarBaz|
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBazVO vo = new FooBarBazVO();
vo.setStart("1");
vo.setEnd("1000000");
FooBarBaz fbb = new FooBarBaz(vo);
fbb.printFooBarBaz();
}
}
++++
++++User Defined Exceptiontitle|
public class FooBarBazException extends Exception {
FooBarBazException(String msg){
super(msg);
}
}
++++
====람다식 개념 ====
++++LambdaFunctionEx.java |
public class LambdaFunctionEx {
public static void main(String[] args) {
interfaceEx ie = (int x, int y) -> x+y;
System.out.println(ie.sum(1, 2));
}
}
interface interfaceEx {
public int sum(int x, int y);
}
++++
==== 함수적 인터페이스 1 ====
++++LambdaEx.java|
public class LambdaEx {
public static void main(String[] args) {
LambdaInterface li = () -> {
String str = "메서드 출력";
System.out.println(str);
};
li.print();
}
}
interface LambdaInterface {
void print();
}
++++
==== 함수적 인터페이스 2 ====
++++LambdaEx2|
public class LambdaEx2 {
public static void main(String[] args) {
System.out.println("시작");
Runnable run = ()-> {
for(int i = 0; i <= 10; i++) {
System.out.println("첫번째 : "+i);
}
};
Runnable run2 = ()-> {
for(int i = 0; i <= 10; i++) {
System.out.println("두번째 : "+i);
}
};
Thread t = new Thread(run);
Thread t2 = new Thread(run2);
t.start();
t2.start();
System.out.println("종료");
}
}
++++
====함수적 인터페이스 3 ====
++++LambdaEx3|
public class LambdaEx3 {
public static void main(String[] args) {
LambdaInterface3 li3 = (String name)->{
System.out.println("제 이름은 "+name+"입니다.");
};
li3.print("홍길동");
}
}
@FunctionalInterface
interface LambdaInterface3{
void print(String name);
}
++++
====함수적 인터페이스 4====
++++LambdaEx4|
public class LambdaEx4 {
public static void main(String[] args) {
LambdaInterface4 f4 = (int x, int y) ->{
return x * y;
};
System.out.println("두 수의 곱 : "+f4.cal(3, 2));
f4 = (x, y) -> x + y;
System.out.println("두 수의 합 : "+f4.cal(3, 2));
f4 = (x, y) -> {return x / y;};
System.out.println("두 수의 몫 : "+f4.cal(5, 2));
f4 = (x, y) -> x%y;
System.out.println("두 수의 나머지 : "+f4.cal(5, 2));
f4 = (x, y) -> sum(x, y);
System.out.println("두 수의 합(sum()) : "+f4.cal(3, 2));
}
static int sum(int x, int y) {
return x + y;
}
}
@FunctionalInterface
interface LambdaInterface4{
int cal(int x, int y);
}
++++
==== 함수적 인터페이스 5 ====
++++LambdaEx5|
public class LambdaEx5 {
public static void main(String[] args) {
Outer o = new Outer();
o.method2();
}
}
@FunctionalInterface
interface LambdaInterface5{
void method();
}
class Outer{
public int iv = 10;
void method2() {
final int iv = 40;
// LambdaInterface5 li5 = new LambdaInterfaceImpl();
LambdaInterface5 li5 = () -> { // 익명 객체 구현 및 익명 함수 구현
System.out.println("Outer.this.iv : "+Outer.this.iv);
System.out.println("this.iv : "+this.iv);
System.out.println("iv : "+iv);
};
li5.method();
}
}
++++
==== Banking Project 버전 1 ====
++++Account|
public class Account {
protected double balance;
protected String name;
protected Account(double initBalance) {
balance = initBalance;
}
public Account(String name) {
balance = 0;
this.name = name;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if(amt <= balance) {
balance = balance+ - amt;
result = true;
}
return result;
}
}
++++
++++CheckingAccount|
public class CheckingAccount extends Account {
private double overdraftAmount = 0;
protected CheckingAccount(double initBalance, double overdraftAmount) {
super(initBalance);
this.overdraftAmount = overdraftAmount;
}
protected CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
protected CheckingAccount(String name) {
super(name);
}
public boolean withdraw(double amount) {
boolean result = true;
if(balance < amount) {
double overdraftNeeded = amount = balance;
if(overdraftAmount < overdraftNeeded) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
}
++++
++++SavingsAccount|
public class SavingsAccount extends Account {
private double interestRate;
protected SavingsAccount(double initBalance, double interestRate) {
super(initBalance);
this.interestRate = interestRate;
}
public SavingsAccount(String name) {
super(name);
this.interestRate = 5.0;
}
}
++++
++++TestTypeSafety|
import java.util.*;
public class TestTypeSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred"));
//lc.add(new SavingsAccount("Fred"));
// therefore...
CheckingAccount ca = lc.get(0);
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
==== Banking Project 버전 2 ====
++++Account|
package com.mybank.domain;
public abstract class Account {
protected double balance;
protected String name;
protected Account(double initBalance) {
balance = initBalance;
}
public Account(String name){
balance = 0;
this.name = name;
}
public abstract double getBalance() ;
public abstract boolean deposit(double amt) ;
public abstract boolean withdraw(double amt) ;
}
++++
++++SavingsAccount|
package com.mybank.domain;
public class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(double initBalance, double interestRate) {
super(initBalance);
this.interestRate = interestRate;
}
public SavingsAccount(String name){
super(name);
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if ( amt <= balance ) {
balance = balance - amt;
result = true; // operation succeeds
}
return result;
}
}
++++
++++CheckingAccount|
package com.mybank.domain;
public class CheckingAccount extends Account {
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
super(initBalance);
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name){
super(name);
}
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
}
++++
++++TestTypeSafety|
import com.mybank.domain.*;
import java.util.*;
public class TestTypeSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred")); // OK
lc.add(new SavingsAccount("Fred")); // Compile error!
// therefore...
CheckingAccount ca = lc.get(0); // Safe, no cast required
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
----
++++Account|
interface Account {
public double getBalance();
public boolean deposit(double amt);
public boolean withdraw(double amt);
}
++++
++++CheckingAccount |
public class CheckingAccount implements Account {
protected double balance;
protected String name;
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
balance = initBalance;
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name) {
balance = 0;
this.name = name;
}
public boolean withdraw(double amount) {
boolean result = true;
if(balance < amount) {
double overdraftNeeded = amount - balance;
if(overdraftAmount < overdraftNeeded) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
}
++++
++++SavingsAccount|
public class SavingsAccount implements Account {
protected double balance;
protected String name;
private double interestRate;
protected SavingsAccount(double initBalance, double interestRate) {
balance = initBalance;
this.interestRate = interestRate;
}
public SavingsAccount(String name) {
balance = 0;
this.name = name;
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if(amt <= balance) {
balance = balance - amt;
result = true; // operation succeds
}
return result;
}
}
++++
++++TestSafety|
import java.util.*;
public class TestSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred"));
//lc.add(new SavingsAccount("Fred"));
// therefore...
CheckingAccount ca = lc.get(0);
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
==== Banking Project 버전 3 ====
++++Account|
package com.mybank.domain;
public interface Account {
public double getBalance() ;
public boolean deposit(double amt) ;
public boolean withdraw(double amt) ;
}
++++
++++SavingsAccount|
package com.mybank.domain;
public class SavingsAccount implements Account {
protected double balance;
protected String name;
private double interestRate;
public SavingsAccount(double initBalance, double interestRate) {
balance = initBalance;
this.interestRate = interestRate;
}
public SavingsAccount(String name){
balance = 0;
this.name = name;
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if ( amt <= balance ) {
balance = balance - amt;
result = true; // operation succeeds
}
return result;
}
}
++++
++++CheckingAccount|
package com.mybank.domain;
public class CheckingAccount implements Account {
protected double balance;
protected String name;
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
balance = initBalance;
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name){
balance = 0;
this.name = name;
}
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
}
++++
++++TestTypeSafety|
import com.mybank.domain.*;
import java.util.*;
public class TestTypeSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred")); // OK
lc.add(new SavingsAccount("Fred")); // Compile error!
// therefore...
CheckingAccount ca = lc.get(0); // Safe, no cast required
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
----
++++Account|
interface Account {
public double getBalance();
public boolean deposit(double amt);
public boolean withdraw(double amt);
}
++++
++++CheckingAccount|
public class CheckingAccount implements Account {
protected double balance;
protected String name;
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
balance = initBalance;
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name) {
balance = 0;
this.name = name;
}
public boolean withdraw(double amount) {
boolean result = true;
if(balance < amount) {
double overdraftNeeded = amount - balance;
if(overdraftAmount < overdraftNeeded) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
}
++++
++++SavingsAccount|
public class SavingsAccount implements Account {
protected double balance;
protected String name;
private double interestRate;
protected SavingsAccount(double initBalance, double interestRate) {
balance = initBalance;
this.interestRate = interestRate;
}
public SavingsAccount(String name) {
balance = 0;
this.name = name;
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if(amt <= balance) {
balance = balance - amt;
result = true; // operation succeds
}
return result;
}
}
++++
++++TestSafety|
import java.util.*;
public class TestSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred"));
//lc.add(new SavingsAccount("Fred"));
// therefore...
CheckingAccount ca = lc.get(0);
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
==== Banking Project ====
++++title|
java code
++++
==== Banking Project (Class Diagram) ====
{{:programmer:java:ㄴhomework:bankingproject_uml.png?400|}}
==== 계산기 프로젝트 (J2SE 버전, 품질10단계, 멀티쓰레드) ====
++++ICal|
interface ICal {
public void doService() throws ArithmeticException, NumberFormatException, AddZeroException, SubZeroException, MulOneException, DivOneException;
}
++++
++++CalImpl|
public class CalImpl implements ICal {
private CalVO vo;
CalImpl(CalVO vo){
this.vo = vo;
}
@Override
public void doService() throws ArithmeticException, NumberFormatException,
AddZeroException, SubZeroException, MulOneException, DivOneException {
int op1 = Integer.parseInt(vo.getOp1());
String op = vo.getOp();
int op2 = Integer.parseInt(vo.getOp2());
if(op.equals(CalVO.ADD)) {
if(op1 == 0 && op2 == 0) {
throw new AddZeroException("+ Zero", 0);
} else if(op1 == 0) {
throw new AddZeroException("+ Zero", op2);
} else if(op2 == 0) {
throw new AddZeroException("+ Zero", op1);
}
} else if(op.equals(CalVO.SUB)) {
if(op1 == 0 && op2 == 0) {
throw new SubZeroException("- Zero", 0);
} else if(op2 == 0) {
throw new SubZeroException("- Zero", op1);
}
} else if(op.equals(CalVO.MUL)) {
if(op1 == 1 && op2 == 1) {
throw new MulOneException("* by One", 1);
} else if(op1 == 1) {
throw new MulOneException("* by One", op2);
} else if(op2 == 1) {
throw new MulOneException("* by One", op1);
}
} else if(op.equals(CalVO.DIV)) {
if(op1 == 1 && op2 == 1) {
throw new DivOneException("/ by One", 1);
} else if(op2 == 1) {
throw new DivOneException("/ by One", op1);
}
}
CalThread cct = new CalThread(vo);
cct.start();
}
}
++++
++++CalThread |
public class CalThread extends Thread {
private CalVO vo;
CalThread(CalVO vo){
this.vo = vo;
}
public void run() {
try {
int op1 = Integer.parseInt(vo.getOp1());
String op = vo.getOp();
int op2 = Integer.parseInt(vo.getOp2());
if(op.equals(CalVO.ADD)) {vo.setResult(op1 + op2);}
else if(op.equals(CalVO.SUB)) {vo.setResult(op1 - op2);}
else if(op.equals(CalVO.MUL)) {vo.setResult(op1 * op2);}
else if(op.equals(CalVO.DIV)) {vo.setResult(op1 / op2);}
System.out.println(vo.getResult());
} catch(ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
} catch(NumberFormatException e) {
System.out.println("숫자 형식이 아닙니다.");
}
}
}
++++
++++CalVO|
public class CalVO {
public static final String ADD = "add";
public static final String SUB = "sub";
public static final String MUL = "mul";
public static final String DIV = "div";
private String op1;
private String op;
private String op2;
private int result;
CalVO(String op1, String op, String op2) {
this.op1 = op1;
this.op = op;
this.op2 = op2;
}
public String getOp1() {
return op1;
}
public void setOp1(String op1) {
this.op1 = op1;
}
public String getOp() {
return op;
}
public void setOp(String op) {
this.op = op;
}
public String getOp2() {
return op2;
}
public void setOp2(String op2) {
this.op2 = op2;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
}
++++
++++Cal|
public class Cal {
private ICal ic;
Cal(CalVO vo){
ic = new CalImpl(vo);
}
void doService() {
try {
ic.doService();
} catch (AddZeroException e) {
System.out.println(e.getMessage()+", result : "+e.getResult());
} catch (SubZeroException e) {
System.out.println(e.getMessage()+", result : "+e.getResult());
} catch (MulOneException e) {
System.out.println(e.getMessage()+", result : "+e.getResult());
} catch (DivOneException e) {
System.out.println(e.getMessage()+", result : "+e.getResult());
} catch (ArithmeticException e) {
System.out.println("0으로 나눌 수 없습니다.");
} catch (NumberFormatException e) {
System.out.println("숫자 형식이 아닙니다.");
} catch (Exception e) {
System.out.println("알 수 없는 예외 발생!");
}
}
}
++++
++++TestCal|
public class TestCal {
public static void main(String[] args) {
// 입력
// 처리
CalVO vo = new CalVO(args[0], args[1], args[2]);
Cal c = new Cal(vo);
// 출력
c.doService();
}
}
++++
++++User Defined Exception|
public class AddZeroException extends Exception {
private int result;
AddZeroException(String msg, int result){
super(msg);
this.result = result;
}
public int getResult() {
return result;
}
}
++++
++++SubZeroException|
public class SubZeroException extends Exception {
private int result;
SubZeroException(String msg, int result){
super(msg);
this.result = result;
}
public int getResult() {
return result;
}
}
++++
++++MulOneException|
public class MulOneException extends Exception {
private int result;
MulOneException(String msg, int result){
super(msg);
this.result = result;
}
public int getResult() {
return result;
}
}
++++
++++DivOneException|
public class DivOneException extends Exception {
private int result;
DivOneException(String msg, int result){
super(msg);
this.result = result;
}
public int getResult() {
return result;
}
}
++++
==== 성적처리 프로젝트 (J2SE 버전, 품질10단계, 멀티쓰레드) ====
++++IScore|
interface IScore {
void doService();
}
++++
++++ScoreImpl|
public class ScoreImpl implements IScore{
private ScoreVO vo;
ScoreImpl(ScoreVO vo){
this.vo = vo;
}
public void doService() {
ScoreThread st = new ScoreThread(vo);
st.start();
}
}
++++
++++ScoreThread|
public class ScoreThread extends Thread {
private ScoreVO vo;
private String[][] score;
ScoreThread(ScoreVO vo){
this.vo = vo;
score = vo.getScore();
}
public void run() {
try {
sum();
avg();
rank();
total();
print();
} catch(ScoreSizeOutOfBoundException e) {
System.out.println("ScoreSizeOutOfBoundException : "+e.getMessage());
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException!!");
} catch(NumberFormatException e) {
System.out.println("NumberFormatException!!");
} catch(NullPointerException e) {
System.out.println("NullPointerException!!");
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생!");
}
}
private void sum() throws ScoreSizeOutOfBoundException, ArrayIndexOutOfBoundsException, NumberFormatException {
for(int i = 0; i < score.length-1; i++) {
int num1 = Integer.parseInt(score[i][1]);
int num2 = Integer.parseInt(score[i][2]);
int num3 = Integer.parseInt(score[i][3]);
if(num1 < ScoreVO.MIN_SCORE || num2 < ScoreVO.MIN_SCORE || num3 < ScoreVO.MIN_SCORE) {
throw new ScoreSizeOutOfBoundException("가능한 점수 범위를 벗어난 값이 입력되었습니다.");
} else if(num1 > ScoreVO.MAX_SCORE || num2 > ScoreVO.MAX_SCORE || num3 > ScoreVO.MAX_SCORE) {
throw new ScoreSizeOutOfBoundException("가능한 점수 범위를 벗어난 값이 입력되었습니다.");
}
int sum = num1 + num2 + num3;
score[i][4] = String.valueOf(sum);
}
}
private void avg() throws ArrayIndexOutOfBoundsException, NumberFormatException {
for(int i = 0; i < score.length-1; i++) {
double avg = (double)Integer.parseInt(score[i][4]) / 3;
avg = ((int)((avg*10) +0.5) / 10d);
score[i][5] = String.valueOf(avg);
}
}
private void rank() throws ArrayIndexOutOfBoundsException, NumberFormatException {
for(int i = 0; i < score.length-1; i++) {
int rank = score.length-1;
for(int j = 0; j < score.length-1; j++) {
if(i != j && Integer.parseInt(score[j][4]) <= Integer.parseInt(score[i][4])) {
rank--;
}
}
score[i][6] = String.valueOf(rank);
}
}
private void total() throws ArrayIndexOutOfBoundsException, NumberFormatException {
int totalSum = 0;
int sum1 = 0;
int sum2 = 0;
int sum3 = 0;
for(int i = 0; i < score.length-1; i++) {
sum1 += Integer.parseInt(score[i][1]);
sum2 += Integer.parseInt(score[i][2]);
sum3 += Integer.parseInt(score[i][3]);
}
totalSum = sum1 + sum2 + sum3;
score[score.length-1][1] = String.valueOf(sum1);
score[score.length-1][2] = String.valueOf(sum2);
score[score.length-1][3] = String.valueOf(sum3);
score[score.length-1][4] = String.valueOf(totalSum);
}
private void print() throws ArrayIndexOutOfBoundsException, NullPointerException {
System.out.println(ScoreVO.LINE);
System.out.println(ScoreVO.TITLE);
System.out.println(ScoreVO.LINE);
for(int i = 0; i < score.length; i++) {
if(i == score.length-1) {System.out.println(ScoreVO.LINE);}
for(int j = 0; j < score[i].length; j++) {
System.out.printf("%-4s ", score[i][j]);
}
System.out.println();
}
}
}
++++
++++ScoreVO|
public class ScoreVO {
public final static int MAX_SCORE = 100;
public final static int MIN_SCORE = 0;
public final static String LINE = "----------------------------------------------";
public final static String TITLE = " 이름 C# JAVA HTML5 합 평균 석차";
private String[][] score;
ScoreVO(String[][] score){
this.score = score;
}
public String[][] getScore() {
return score;
}
public void setScore(String[][] score) {
this.score = score;
}
}
++++
++++Score|
public class Score {
private IScore is;
Score(ScoreVO vo){
is = new ScoreImpl(vo);
}
void doService() {
is.doService();
}
}
++++
++++TestScore|
public class TestScore {
public static void main(String[] args) {
// 1. 입력
String[][] score = {{"홍길동", "90", "80", "70", "?", "?", "?"},
{"강감찬", "80", "90", "70", "?", "?", "?"},
{"유관순", "80", "30", "60", "?", "?", "?"},
{"이순신", "80", "20", "60", "?", "?", "?"},
{"김갑순", "70", "90", "60", "?", "?", "?"},
{"총 점", "?", "?", "?", "?", "-", "-"},
};
// 2. 처리
ScoreVO vo = new ScoreVO(score);
Score s = new Score(vo);
// 3. 결과
s.doService();
}
}
++++
++++User Defined Exception|
public class ScoreSizeOutOfBoundException extends Exception {
ScoreSizeOutOfBoundException(String msg){
super(msg);
}
}
++++
==== 엘리베이터 프로젝트 (J2SE 버전, 품질10단계, 멀티쓰레드) ====
++++IElevator|
interface IElevator {
public void openDoor();
public void closeDoor();
public void goUp() throws CannotGoUpException;
public void goDown() throws CannotGoDownException;
public void setFloor(String desiredFloor) throws ArrayIndexOutOfBoundsException, NumberFormatException, CannotGoUpException, CannotGoDownException;
}
++++
++++ElevatorImpl|
public class ElevatorImpl implements IElevator {
private ElevatorVO vo;
ElevatorImpl(ElevatorVO vo){
this.vo = vo;
}
public void openDoor() {
OpenDoorThread od = new OpenDoorThread(vo);
od.start();
try {
od.join();
} catch (InterruptedException e) {}
}
public void closeDoor() {
CloseDoorThread cd = new CloseDoorThread(vo);
cd.start();
try {
cd.join();
} catch (InterruptedException e) {}
}
public void goUp() throws CannotGoUpException {
if(vo.getCurrentFloor() == vo.getTOP_FLOOR()) {
throw new CannotGoUpException("Cannot Go up");
} else {
GoUpThread gu = new GoUpThread(vo);
gu.start();
try {
gu.join();
} catch (InterruptedException e) {}
}
}
public void goDown() throws CannotGoDownException {
if(vo.getCurrentFloor() == vo.getMIN_FLOORS()) {
throw new CannotGoDownException("Cannot Go Down");
} else {
GoDownThread gd = new GoDownThread(vo);
gd.start();
try {
gd.join();
} catch (InterruptedException e) {}
}
}
public void setFloor(String PdesiredFloor) throws NumberFormatException, CannotGoUpException, CannotGoDownException {
vo.setDesiredFloor(Integer.parseInt(PdesiredFloor));
while(vo.getCurrentFloor() != vo.getDesiredFloor()) {
if(vo.getCurrentFloor() < vo.getDesiredFloor()) {
goUp();
} else {
goDown();
}
}
}
}
++++
----
**Thread inheritance class**
++++CloseDoorThread|
public class CloseDoorThread extends Thread {
private ElevatorVO vo;
CloseDoorThread(ElevatorVO vo){
this.vo = vo;
}
@Override
public void run() {
System.out.println("Closing door");
vo.setDoorOpen(false);
System.out.println("Door is closed");
}
}
++++
++++OpenDoorThread|
public class OpenDoorThread extends Thread {
private ElevatorVO vo;
OpenDoorThread(ElevatorVO vo){
this.vo = vo;
}
@Override
public void run() {
System.out.println("Opening door");
vo.setDoorOpen(true);
System.out.println("Door is open");
}
}
++++
++++GoUpThread|
public class GoUpThread extends Thread {
private ElevatorVO vo;
GoUpThread(ElevatorVO vo){
this.vo = vo;
}
@Override
public void run() {
System.out.println("Going up one floor");
vo.setCurrentFloor(vo.getCurrentFloor()+1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
++++
++++GoDownThread |
public class GoDownThread extends Thread {
private ElevatorVO vo;
GoDownThread(ElevatorVO vo){
this.vo = vo;
}
@Override
public void run() {
System.out.println("Going down one floor");
vo.setCurrentFloor(vo.getCurrentFloor()-1);
System.out.println("Floor: "+vo.getCurrentFloor());
}
}
++++
++++ElevatorVO|
public class ElevatorVO {
private final static int TOP_FLOOR = 10;
private final static int MIN_FLOORS = 1;
private int currentFloor = 1;
private boolean doorOpen = false;
private int desiredFloor;
public boolean isDoorOpen() {
return doorOpen;
}
public void setDoorOpen(boolean doorOpen) {
this.doorOpen = doorOpen;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
public int getTOP_FLOOR() {
return TOP_FLOOR;
}
public int getMIN_FLOORS() {
return MIN_FLOORS;
}
public int getDesiredFloor() {
return desiredFloor;
}
public void setDesiredFloor(int desiredFloor) {
this.desiredFloor = desiredFloor;
}
}
++++
++++Elevator|
public class Elevator {
private IElevator ie;
Elevator(ElevatorVO vo){
ie = new ElevatorImpl(vo);
}
public void openDoor() {
ie.openDoor();
}
public void closeDoor() {
ie.closeDoor();
}
public void goUp() {
try {
ie.goUp();
} catch(CannotGoUpException e) {
System.out.println("CannotGoUpException : "+e.getMessage());
}
}
public void goDown() {
try {
ie.goDown();
} catch(CannotGoDownException e) {
System.out.println("CannotGoDownException : "+e.getMessage());
}
}
public void setFloor(String desiredFloor) {
try {
ie.setFloor(desiredFloor);
} catch(NumberFormatException e) {
System.out.println("NumberFormatException !!");
} catch(CannotGoUpException e) {
System.out.println("CannotGoUpException : "+e.getMessage());
} catch(CannotGoDownException e) {
System.out.println("CannotGoDownException : "+e.getMessage());
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생 !!");
}
}
}
++++
++++ElevatorTest|
public class ElevatorTest{
public static void main(String[] args) {
ElevatorVO vo = new ElevatorVO();
Elevator myElevator = new Elevator(vo);
String desiredFloor = args[0];
myElevator.openDoor();
myElevator.closeDoor();
myElevator.goUp();
myElevator.goUp();
myElevator.goUp();
myElevator.goDown();
myElevator.setFloor(desiredFloor);
}
}
++++
----
**User Defined Exception**
++++CannotGoUpException|
public class CannotGoUpException extends Exception {
CannotGoUpException(String msg){
super(msg);
}
}
public class CannotGoDownException extends Exception {
CannotGoDownException(String msg){
super(msg);
}
}
++++
==== FooBarBaz 프로젝트 (J2SE 버전, 품질10단계, 멀티쓰레드) ====
++++IFooBarBaz|
interface IFooBarBaz {
void printFooBarBaz() throws NumberFormatException;
}
++++
++++FooBarBazImpl|
public class FooBarBazImpl implements IFooBarBaz {
FooBarBazVO vo;
FooBarBazImpl(FooBarBazVO vo){
this.vo = vo;
}
@Override
public void printFooBarBaz() throws NumberFormatException {
int start = Integer.parseInt(vo.getStart());
int end = Integer.parseInt(vo.getEnd());
FooBarBazThread fbbt = new FooBarBazThread(vo);
fbbt.start();
}
}
++++
++++FooBarBazThread|
public class FooBarBazThread extends Thread {
FooBarBazVO vo;
FooBarBazThread(FooBarBazVO vo){
this.vo = vo;
}
@Override
public void run() {
try{
int start = Integer.parseInt(vo.getStart());
int end = Integer.parseInt(vo.getEnd());
for(int i = start; i < end; i++) {
System.out.print(i);
if(i % FooBarBazVO.THREE == 0) {
System.out.print(" "+FooBarBazVO.FOO);
}
if(i % FooBarBazVO.FIVE == 0) {
System.out.print(" "+FooBarBazVO.BAR);
}
if(i % FooBarBazVO.SEVEN == 0) {
System.out.print(" "+FooBarBazVO.BAZ);
}
System.out.println();
if((i % FooBarBazVO.THREE == 0) && (i % FooBarBazVO.FIVE == 0) && (i % FooBarBazVO.SEVEN == 0)) {
throw new FooBarBazException("축하합니다! "+ FooBarBazVO.FOO_BAR_BAZ +"입니다!");
}
}
System.out.println();
System.out.print("and so on.");
} catch(NumberFormatException e) {
System.out.println("입력된 값이 숫자 포맷이 아닙니다.");
} catch(FooBarBazException e) {
System.out.println(e.getMessage());
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생!");
}
}
}
++++
++++FooBarBazVO|
public class FooBarBazVO {
public final static String FOO = "foo";
public final static String BAR = "bar";
public final static String BAZ = "baz";
public final static String FOO_BAR_BAZ = "foo bar baz";
public final static int THREE = 3;
public final static int FIVE = 5;
public final static int SEVEN = 7;
private String start;
private String end;
public String getStart() {
return start;
}
public void setStart(String start) {
this.start = start;
}
public String getEnd() {
return end;
}
public void setEnd(String end) {
this.end = end;
}
}
++++
++++FooBarBaz|
public class FooBarBaz {
IFooBarBaz ifbb;
FooBarBaz(FooBarBazVO vo){
ifbb = new FooBarBazImpl(vo);
}
void printFooBarBaz() {
try {
ifbb.printFooBarBaz();
} catch(NumberFormatException e) {
System.out.println("NumberFormatException! ");
} catch(Exception e) {
System.out.println("알 수 없는 예외 발생!");
}
}
}
TestFooBarBaz
public class TestFooBarBaz {
public static void main(String[] args) {
FooBarBazVO vo = new FooBarBazVO();
vo.setStart("1");
vo.setEnd("150");
FooBarBaz fbb = new FooBarBaz(vo);
fbb.printFooBarBaz();
}
}
++++
----
**User Defined Exception**
++++FooBarBazException|
public class FooBarBazException extends Exception {
FooBarBazException(String msg){
super(msg);
}
}
++++
==== Banking Project (J2SE 버전, 품질1단계) ====
**예제**
++++Account|
package com.mybank.domain;
public interface Account {
public double getBalance() ;
public boolean deposit(double amt) ;
public boolean withdraw(double amt) ;
}
++++
++++title|
package com.mybank.domain;
public class SavingsAccount implements Account {
protected double balance;
protected String name;
private double interestRate;
public SavingsAccount(double initBalance, double interestRate) {
balance = initBalance;
this.interestRate = interestRate;
}
public SavingsAccount(String name){
balance = 0;
this.name = name;
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false; // assume operation failure
if ( amt <= balance ) {
balance = balance - amt;
result = true; // operation succeeds
}
return result;
}
}
++++
++++CheckingAccount|
package com.mybank.domain;
public class CheckingAccount implements Account {
protected double balance;
protected String name;
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
balance = initBalance;
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name){
balance = 0;
this.name = name;
}
public boolean withdraw(double amount) {
boolean result = true;
if ( balance < amount ) {
double overdraftNeeded = amount - balance;
if ( overdraftAmount < overdraftNeeded ) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
}
++++
++++TestTypeSafety|
import com.mybank.domain.*;
import java.util.*;
public class TestTypeSafety {
public static void main(String[] args) {
List lc = new ArrayList();
lc.add(new CheckingAccount("Fred")); // OK
lc.add(new SavingsAccount("Fred")); // Compile error!
// therefore...
CheckingAccount ca = lc.get(0); // Safe, no cast required
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
}
}
++++
----
++++TestAccount|
public class TestAccount {
private double sBalance;
private String sName;
private double interestRate;
private double cBalance;
private String cName;
private double overdraftAmount = 0;
public boolean sDeposit(double amt) {
sBalance = sBalance + amt;
return true;
}
public boolean sWithdraw(double amt) {
boolean result = false;
if(amt <= sBalance) {
sBalance = sBalance - amt;
result = true;
}
return result;
}
public boolean cDeposit(double amt) {
cBalance = cBalance + amt;
return true;
}
public boolean cWithdraw(double amount) {
boolean result = true;
if(cBalance < amount) {
double overdraftNeeded = amount - cBalance;
if(overdraftAmount < overdraftNeeded) {
result = false;
} else {
cBalance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
cBalance = cBalance - amount;
}
return result;
}
public static void main(String[] args) {
TestAccount ts = new TestAccount();
System.out.println("Withdraw 150.00 : " + ts.cWithdraw(150.00));
System.out.println("Deposit 22.50 : " + ts.cDeposit(22.50));
System.out.println("Withdraw 47.62 : " + ts.cWithdraw(47.62));
System.out.println("Withdraw 400.00 : " + ts.cWithdraw(400.00));
System.out.println("Balance : " + ts.cBalance);
System.out.println("=========================================");
System.out.println("Withdraw 150.00 : " + ts.sWithdraw(150.00));
System.out.println("Deposit 22.50 : " + ts.sDeposit(22.50));
System.out.println("Withdraw 47.62 : " + ts.sWithdraw(47.62));
System.out.println("Withdraw 400.00 : " + ts.sWithdraw(400.00));
System.out.println("Balance : " + ts.sBalance);
}
}
++++
==== Banking Project (J2SE 버전, 품질2단계) ====
++++SavingsAccount|
public class SavingsAccount {
private double balance;
private String name;
private double interestRate;
public SavingsAccount(double initBalance, double interestRate) {
balance = initBalance;
this.interestRate = interestRate;
}
public SavingsAccount(String name) {
balance = 0;
this.name = name;
this.interestRate = 5.0;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amt) {
boolean result = false;
if(amt <= balance) {
balance = balance - amt;
result = true;
}
return result;
}
}
++++
++++CheckingAccount|
public class CheckingAccount {
private double balance;
private String name;
private double overdraftAmount = 0;
public CheckingAccount(double initBalance, double overdraftAmount) {
balance = initBalance;
this.overdraftAmount = overdraftAmount;
}
public CheckingAccount(double initBalance) {
this(initBalance, 0.0);
}
public CheckingAccount(String name) {
balance = 0;
this.name = name;
}
public double getBalance() {
return balance;
}
public boolean deposit(double amt) {
balance = balance + amt;
return true;
}
public boolean withdraw(double amount) {
boolean result = true;
if(balance < amount) {
double overdraftNeeded = amount - balance;
if(overdraftAmount < overdraftNeeded) {
result = false;
} else {
balance = 0.0;
overdraftAmount -= overdraftNeeded;
}
} else {
balance = balance - amount;
}
return result;
}
}
++++
++++TestSafety|
import java.util.ArrayList;
import java.util.List;
public class TestSafety {
public static void main(String[] args) {
List lc = new ArrayList();
List ls = new ArrayList();
lc.add(new CheckingAccount("Fred"));
ls.add(new SavingsAccount("Fred"));
CheckingAccount ca = lc.get(0);
SavingsAccount sa = ls.get(0);
System.out.println("Withdraw 150.00 : " + ca.withdraw(150.00));
System.out.println("Deposit 22.50 : " + ca.deposit(22.50));
System.out.println("Withdraw 47.62 : " + ca.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + ca.withdraw(400.00));
System.out.println("Balance : " + ca.getBalance());
System.out.println("=========================================");
System.out.println("Withdraw 150.00 : " + sa.withdraw(150.00));
System.out.println("Deposit 22.50 : " + sa.deposit(22.50));
System.out.println("Withdraw 47.62 : " + sa.withdraw(47.62));
System.out.println("Withdraw 400.00 : " + sa.withdraw(400.00));
System.out.println("Balance : " + sa.getBalance());
}
}
++++
==== 과제 93 ====
++++title|
java code
++++
==== 과제 94 ====
++++title|
java code
++++
==== 과제 95 ====
++++title|
java code
++++
==== 과제 96 ====
++++title|
java code
++++
==== 과제 97 ====
++++title|
java code
++++
==== 과제 98 ====
++++title|
java code
++++
==== 과제 99 ====
++++title|
java code
++++
==== 과제 100 ====
++++title|
java code
++++
==== 과제 101 ====
++++title|
java code
++++
==== 과제 102 ====
++++title|
java code
++++