문서의 이전 판입니다!
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 오버라이딩
System.out.println(“ ”)라인 출력하기
“\n” 줄 칸 띄우기
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.
System.out.printf("%4s", "문자열"); //문자의 자릿수를 정해줌.
for 구문
for(변수 선언; 변수의 사용범위; 변수에 대한 명령){}
for(int i=0; i<10; i++){
if 구문을 통한 반복되는 문자열 추가
if (i % 3 == 0) { System.out.printf("%4s", "foo")
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.
학점 계산기를 만들기 위한 값의 구조
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 +="-"; }
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-입니다.
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;
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입니다.");
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이고, 상품은 자동차입니다. 죄송하지만 당신의 점수는 해당상품이 없습니다.
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이고, 상품은 자동차입니다. 죄송하지만 당신의 점수는 해당상품이 없습니다.
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 +"점 이상 입니다."); } }
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점 이상입니다.
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점 이상입니다.
argument 입력
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
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("죄송하지만 당신의 점수에 해당상품이 없습니다."); } } }
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이고, 상품은 자동차입니다. 죄송하지만 당신의 점수는 해당상품이 없습니다.
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 + "입니다."); } }
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이고, 상품은 자동차입니다. 죄송하지만 당신의 점수는 해당상품이 없습니다.
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
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점 이상입니다.
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 + "입니다."); } }
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점 이상입니다.
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) } }
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); } } } }
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
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); } } }
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); } } } }
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
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'); } }
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); } } }
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
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); } }
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); } }
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
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 ); } } } }
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++; } } }
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); } }
다음 프로그램을 근거로, 도표를 작성하시오.
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); } }———————-
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); } }
다음 프로그램을 근거로, 도표를 작성하시오.
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); } }
다음 프로그램을 근거로, 도표를 작성하시오.
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
다음 프로그램을 근거로, 도표를 작성하시오.
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 <source.length(); i++) { result += morse[source.charAt(i)-'A']; System.out.printf("%2d %s %c %-2d " + " %-4s %s\n", i, source, source.charAt(i), source.charAt(i)-'A', morse[i], result); } System.out.println("source:"+source); System.out.println("morse:"+result); }// end of main }// end of class
다음 프로그램을 근거로, 도표를 작성하시오.
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
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
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. 입력
———————————————–
이름 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(); } } }
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 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(); } } }
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(); } }
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 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(); } } }
public class Score extends PScore{ Score(String[][] score) { super(score); } }
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(); } }
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 abstract class PScore { abstract void sum(); abstract void avg(); abstract void rank(); abstract void total(); abstract void print(); }
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(); } } }
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(); } }
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 ? ?
———————————————————-
총점 ? ? ? ? -
———————————————————-
interface IScore { void sum(); void avg(); void rank(); void total(); void print(); }
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(); } } }
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(); } }
Integer.pharseInt 사용
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
메서드 정의 사용하기
public class TestCal { public static void main(String[] args) { Cal c = new Cal(); c.doCal(args); c.getResult(); } }
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
상속관계를 사용
public class TestCal { public static void main(String[] args) { Cal c = new Cal(); c.doCal(args); c.getResult(); } }
public class Cal extends 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
상속 + 메서드 정의
public class TestCal { public static void main(String[] args) { Cal c = new Cal(); c.doCal(args); c.getResult(); } }
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); }
abstract class CalP { abstract void doCal(String[] args); abstract void getResult(); }
결과 :
8
interface 의 사용
public class TestCal { public static void main(String[] args) { CalImpl ic = new CalImpl(); ic.doCal(args); ic.getResult(); } }
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); } }
interface ICal { void doCal(String[] args); void getResult(); }
결과 :
8
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."); } }
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."); } }
public class TestFooBarBaz { public static void main(String[] args) { FooBarBaz fz = new FooBarBaz(); fz.printFooBarBaz(); } }
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."); } }
public class FooBarBaz extends PFooBarBaz { }
public abstract class TestFooBarBaz { public static void main(String[] args) { FooBarBaz fz = new FooBarBaz(); fz.printFooBarBaz(); } }
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."); } }
public abstract class PFooBarBaz { abstract void printFooBarBaz(); }
public abstract class TestFooBarBaz { public static void main(String[] args) { FooBarBaz fz = new FooBarBaz(); fz.printFooBarBaz(); } }
interface IFooBarBaz { void printFooBarBaz(); }
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."); } }
public abstract class TestFooBarBaz { public static void main(String[] args) { IFooBarBaz fz = new FooBarBazImpl(); fz.printFooBarBaz(); } }
Loose Abstract Coupling
interface ICal { public void calc(); public void printResult(); }
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); } }
public class Cal { ICal ic; Cal(String[] args){ ic = new CalImpl(args); } void calc() { ic.calc(); } void printResult() { ic.printResult(); } }
public class TestCal { public static void main(String[] args) { // 입력 // 처리 Cal c = new Cal(args); c.calc(); // 출력 c.printResult(); } }
interface IScore { void doService(); void print(); }
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(); } } }
public class Score { IScore is; Score(String[][] score){ is = new ScoreImpl(score); } void doService() { is.doService(); } void print() { is.print(); } }
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(); } }
interface IFooBarBaz { void printFooBarBaz(); }
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."); } }
public class FooBarBaz { IFooBarBaz fb; FooBarBaz(){ fb = new FooBarBazImpl(); } void printFooBarBaz() { fb.printFooBarBaz(); } }
public class TestFooBarBaz { public static void main(String[] args) { FooBarBaz fb = new FooBarBaz(); fb.printFooBarBaz(); } }
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); } }
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); } }
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(); } }
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(); } }
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); } } }
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(); } }
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(); } }
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); } } } }
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(); } }
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(); } }
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); } } }
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(); } }
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(); } }
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(); } } } }
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(); } }
do ~while문을 활용해서 Refactoring
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); } }
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(); } }
엘레베이터 프로젝트 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(); } } } }
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(); } } } }
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(); } }
문제 : 객체를 생성할 때마다 카운트를 하여, 총 몇 개의 객체가 생성되었는지 출력하는 프로그램을 작성하시오.
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()); } }
문제 : 객체를 생성할 때마다 카운트를 하여, 총 몇 개의 객체가 생성되었는지 출력하는 프로그램을 작성하시오.
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()); } }
public class Counter { private static int count; Counter(){ count++; } public static int getCount() { return count; } }
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()); } }
public class PCounter { private static int count; PCounter(){ count++; } public static int getCount() { return count; } }
public class Counter extends PCounter { }
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()); } }
public abstract class PCounter { }
public class Counter extends PCounter { private static int count; Counter(){ count++; } public static int getCount() { return count; } }
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()); } }
interface ICounter { }
public class Counterimpl implements ICounter { private static int count; Counterimpl(){ count++; } public static int getCount() { return count; } } </java> ++++ ++++| <code java> </java> ++++ ++++TestCounter | <code java> 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()); } }
interface ICounter { }
public class CounterImpl implements ICounter { private static int count; CounterImpl(){ count++; } public static int getCount() { return count; } }
public class Counter { private ICounter ci; Counter(){ ci = new CounterImpl(); } public static int getCount() { return CounterImpl.getCount(); } }
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()); } }
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); } }
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); } }
public class TestRsp { public static void main(String[] args) { Rsp r = new Rsp(); r.playRsp(); r.printResult(); } }
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); } }
public class Rsp extends PRsp{ }
public class TestRsp { public static void main(String[] args) { Rsp r = new Rsp(); r.playRsp(); r.printResult(); } }
public abstract class PRsp { public abstract void playRsp(); public abstract void printResult(); }
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); } }
public class TestRsp { public static void main(String[] args) { Rsp r = new Rsp(); r.playRsp(); r.printResult(); } }
interface IRsp { void playRsp(); void printResult(); }
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); } }
public class TestRsp { public static void main(String[] args) { IRsp r = new RspImpl(); r.playRsp(); r.printResult(); } }
interface IRsp { void playRsp(); void printResult(); }
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); } }
public class Rsp { IRsp ir; Rsp(){ ir = new Rspimpl(); } public void playRsp() { ir.playRsp(); } public void printResult() { ir.printResult(); } }
public class TestRsp { public static void main(String[] args) { Rsp r = new Rsp(); r.playRsp(); r.printResult(); } }
interface ICal { public void calc(CalVO vo); public void printResult(CalVO vo); }
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()); } }
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; } }
public class Cal { ICal ic; Cal(){ ic = new CalImpl(); } void calc(CalVO vo) { ic.calc(vo); } void printResult(CalVO vo) { ic.printResult(vo); } }
public class TestCal { public static void main(String[] args) { // 입력 // 처리 CalVO vo = new CalVO(args); Cal c = new Cal(); c.calc(vo); // 출력 c.printResult(vo); } }
interface IScore { void doService(); void print(); }
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(); } } }
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; } }
public class Score { IScore is; Score(ScoreVO vo){ is = new ScoreImpl(vo); } void doService() { is.doService(); } void print() { is.print(); } }
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(); } }
interface IFooBarBaz { void printFooBarBaz(FooBarBazVO vo); }
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()); } }
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; } }
public class FooBarBaz { IFooBarBaz fb; FooBarBaz(){ fb = new FooBarBazImpl(); } void printFooBarBaz(FooBarBazVO vo) { fb.printFooBarBaz(vo); } }
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); } }
interface IElevator { public void openDoor(); public void closeDoor(); public void goUp(); public void goDown(); public void setFloor(int desiredFloor); }
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(); } } } }
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; } }
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); } }
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(); } }
interface ICal { public void doService(); }
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(); } }
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; } }
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!!"); } } }
public class TestCal { public static void main(String[] args) { // 입력 // 처리 CalVO vo = new CalVO(args); Cal c = new Cal(vo); // 출력 c.doService(); } }
예외처리, Built-In
interface IScore { void doService(); void print(); }
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(); } } }
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(); } } }
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; } }
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!!"); } } }
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(); } }
interface IElevator { public void openDoor(); public void closeDoor(); public void goUp(); public void goDown(); public void setFloor(String desiredFloor); }
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(); } } } }
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; } }
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("알 수 없는 예외 발생 !!"); } } }
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(); } }
예외처리, Built-in
interface IFooBarBaz { void printFooBarBaz(FooBarBazVO vo); }
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()); } }
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; } }
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!!"); } } }
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); } }
예외처리, User-Defined
interface IScore { void doService() throws ArrayIndexOutOfBoundsException, NumberFormatException, ScoreSizeOutOfBoundException; }
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(); } } }
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; } }
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("알 수 없는 예외 발생!"); } } }
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(); } }
public class ScoreSizeOutOfBoundException extends Exception { ScoreSizeOutOfBoundException(String msg){ super(msg); } }
성적처리 프로젝트 (J2SE, 품질9단계, 예외처리, User-Defined)
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"); }
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; }
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(); } } } }
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; } }
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("알 수 없는 예외 발생 !!"); } } }
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(); } }
public class CannotGoDownException extends Exception { CannotGoDownException(String msg){ super(msg); } }
public class CannotGoUpException extends Exception { CannotGoUpException(String msg){ super(msg); } }
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(); } }
interface IFooBarBaz { void printFooBarBaz() throws FooBarBazException; }
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."); } }
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; } }
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! "); } } }
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(); } }
public class FooBarBazException extends Exception { FooBarBazException(String msg){ super(msg); } }
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); }
public class LambdaEx { public static void main(String[] args) { LambdaInterface li = () -> { String str = "메서드 출력"; System.out.println(str); }; li.print(); } } interface LambdaInterface { void print(); }
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("종료"); } }
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); }
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); }
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(); } }
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; } }
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; } }
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; } }
import java.util.*; public class TestTypeSafety { public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<CheckingAccount>(); 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()); } }
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) ; }
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; } }
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; } }
import com.mybank.domain.*; import java.util.*; public class TestTypeSafety { public static void main(String[] args) { List<CheckingAccount> lc = new ArrayList<CheckingAccount>(); 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()); } }
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code
java code