1. 버그
: 논리적인 오류
2. 디버깅
: 시작점(breakpoint) 설정
> 벌레 모양 클릭 혹은 단축키 F11 이용
> 디버그 관점으로 바꾸기
> 디버그 모드에서 봐야하는 화면은 ①②③임(① 메소드 확인, ② 콘솔 출력 확인, ③ 변수값 확인)
[추가] 디버그 종료 버튼과 디버그 관점 추가 확인하기
[추가] 최종적으로 디버그 모드가 종료되면 빨간색 종료버튼이 회색으로 변경됨
3. 제어문
1) 조건문(Conditional, branch, selection)
: if~else, switch~case
2) 순환문(loop, iteration)
: for, while, do~while
4. for문과 while문은 100% 전환 가능
5. 코딩 문제 은행
: http://jungol.co.kr/
[실습코드]
1. Lec06_if
1) com.lec.java.if01 패키지, If01Main 클래스
package com.lec.java.if01;
/* if, if ~ else 조건문
*
* 구문1:
* if (조건식) {
* 조건식이 true 일때 실행되는 문장(들)
* ...
* }
*
* 구문2:
* if (조건식) {
* 조건식이 true 일때 실행되는 문장(들)
* ...
* } else {
* 조건식이 false 일때 실행되는 문장(들)
* ...
* }
*/
public class If01Main {
public static void main(String[] args) {
System.out.println("if 조건문");
int num = -10;
if (num > 0) {
// num의 값이 0보다 작기 때문에 false
// 따라서 해당 조건문은 실행되지 않음
System.out.println("양수입니다.");
}
if (num < 0) {
System.out.println("음수입니다.");
}
if (num > 0) {
System.out.println(num + "은 양수입니다!!!!");
} else {
System.out.println(num + "은 양수가 아닙니다!!!!");
}
System.out.println();
// 수행 문장이 하나뿐이면 굳이 {...} 블럭 안 잡아도 된다.
if (num > 0)
System.out.println(num + " -> 음수");
else
System.out.println(num + " -> 0 혹은 양수");
// 주어진 숫자가 짝수/홀수 인지 여부
int num3 = 123;
//int num3 = 124;
if(num3 % 2 == 0) {
System.out.println(num3 + "는 짝수입니다.");
} else {
System.out.println(num3 + "는 홀수입니다.");
}
// 주어진 숫자가 0 ~ 100점까지 범위인지 여부
int num4 = 101;
//int num4 = -40;
//int num4 = 40;
//if(0 <= num4 <= 100) //자바는 이런 조건식 표현 불가
if(0 <= num4 && num4 <= 100) {
System.out.println(num4 + "는 유효한 점수입니다.");
} else {
System.out.println(num4 + "는 유효점수가 아닙니다.");
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
2) com.lec.java.if02 패키지, If02Main 클래스
package com.lec.java.if02;
/* if ~ else if ~ else조건식
*
* 구문3:
* if (조건식1) {
* 조건식1 이 true 일때 실행되는 문장(들)
* ...
* } else if (조건식2) {
* 조건식1 이 false 이고
* 조건식2 이 true 일때 실행되는 문장(들)
* ...
* } else if (조건식3) {
* 조건식2 가 false 이고
* 조건식3 이 true 일때 실행되는 문장(들)
* ...
* } else {
* 위의 모든 조건식 모두 false 일때 수행하는 문장(들)
* ..
* }
*
*/
public class If02Main {
public static void main(String[] args) {
System.out.println("if - else if - else");
int kor = 68;
int eng = 60;
int math = 63;
// int kor = 88;
// int eng = 80;
// int math = 83;
int total = kor + eng + math; // 총점
int avg = total / 3; // 평균
// 1. 평균이 90점 이상이면 A학점 (평균: 90 ~ 100)
// 2. 평균이 80점 이상이면 B학점 (평균: 80 ~ 89)
// 3. 평균이 70점 이상이면 C학점 (평균: 70 ~ 79)
// 4. 평균이 60점 이상이면 D학점 (평균: 60 ~ 69)
// 5. 평균이 60점 미만이면 F학점
System.out.println("평균 : " + avg);
if(avg >= 90) {
// 1.
System.out.println("학점 : A");
} else if(avg >= 80) {
// 2.
System.out.println("학점 : B");
} else if(avg >= 70) {
// 3.
System.out.println("학점 : C");
} else if(avg >= 60) {
// 4.
System.out.println("학점 : D");
} else {
// 5.
System.out.println("학점 : F, 이번 학기는 글렀어 ㅜ^ㅜ");
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
3) com.lec.java.if03 패키지, If03Main 클래스
** 내가 작성한 코드 **
package com.lec.java.if03;
import java.util.Scanner;
/* if 조건문 연습 : 간단한 성적 처리 프로그램
* 사용자로부터 국어,영어,수학 점수 (정수) 를 입력 받은뒤
* 우선 '총점' 과 '평균' 을 계산해서 출력하고
*
* '학점'을 아래와 같이 출력하세요
* 평균이 90점 이상이면 "A학점" 출력 (평균: 90 ~ 100)
* 평균이 80점 이상이면 "B학점" 출력 (평균: 80 ~ 89)
* 평균이 70점 이상이면 "C학점" 출력 (평균: 70 ~ 79)
* 평균이 60점 이상이면 "D학점" 출력 (평균: 60 ~ 69)
* 평균이 60점 미만이면 "F학점" 출력
*/
public class If03Main {
public static void main(String[] args) {
System.out.println("간단한 성적 처리 프로그램");
Scanner sc = new Scanner(System.in);
int kor = 0, math = 0, eng = 0;
char grade = ' ';
int total = 0;
double avg = 0.0;
System.out.println("국어 점수 입력 : ");
kor = sc.nextInt();
System.out.println("수학 점수 입력 : ");
math = sc.nextInt();
System.out.println("영어 점수 입력 : ");
eng = sc.nextInt();
sc.close();
total = kor + math + eng;
avg = total / 3.0;
if(avg >= 90) {
// 1.
grade = 'A';
} else if(avg >= 80) {
// 2.
grade = 'B';
} else if(avg >= 70) {
// 3.
grade = 'C';
} else if(avg >= 60) {
// 4.
grade = 'D';
} else {
// 5.
grade = 'F';
}
System.out.println("----- 입력한 점수 -----");
System.out.println("국어 : " + kor);
System.out.println("수학 : " + math);
System.out.println("영어 : " + eng);
System.out.println("총점 : " + total);
System.out.println("평균 : " + String.format("%.1f", avg));
System.out.println("학점 : " + grade);
System.out.println();
System.out.println("\n프로그램 종료");
} // end main()
} // end class
** 쌤이 작성해주신 코드 **
package com.lec.java.if03;
import java.util.Scanner;
/* if 조건문 연습 : 간단한 성적 처리 프로그램
* 사용자로부터 국어,영어,수학 점수 (정수) 를 입력 받은뒤
* 우선 '총점' 과 '평균' 을 계산해서 출력하고
*
* '학점'을 아래와 같이 출력하세요
* 평균이 90점 이상이면 "A학점" 출력 (평균: 90 ~ 100)
* 평균이 80점 이상이면 "B학점" 출력 (평균: 80 ~ 89)
* 평균이 70점 이상이면 "C학점" 출력 (평균: 70 ~ 79)
* 평균이 60점 이상이면 "D학점" 출력 (평균: 60 ~ 69)
* 평균이 60점 미만이면 "F학점" 출력
*/
public class If03Main {
public static void main(String[] args) {
System.out.println("간단한 성적 처리 프로그램");
// 입력 받을 준비 - Scanner
Scanner sc = new Scanner(System.in);
// 국어 점수를 입력받아서 저장
int korean;
System.out.println("국어 점수 입력:");
korean = sc.nextInt();
// 수학 점수를 입력받아서 저장
int math;
System.out.println("수학 점수 입력:");
math = sc.nextInt();
// 영어 점수를 입력받아서 저장
int english;
System.out.println("영어 점수 입력:");
english = sc.nextInt();
// 사용이 끝난 Scanner를 닫아줌
sc.close();
// 입력받은 점수들 확인
System.out.println("----- 입력한 점수 -----");
System.out.println("국어: " + korean);
System.out.println("수학: " + math);
System.out.println("영어: " + english);
// 총점 계산
int total = korean + math + english;
System.out.println("총점: " + total);
// 평균 계산
double average = (double) total / 3;
System.out.println("평균: " + average);
// 1. 평균이 90점 이상이면 A학점 (평균: 90 ~ 100)
// 2. 평균이 80점 이상이면 B학점 (평균: 80 ~ 89)
// 3. 평균이 70점 이상이면 C학점 (평균: 70 ~ 79)
// 4. 평균이 60점 이상이면 D학점 (평균: 60 ~ 69)
// 5. 평균이 60점 미만이면 F학점
if (average >= 90) {
System.out.println("학점: A");
} else if (average >= 80) {
System.out.println("학점: B");
} else if (average >= 70) {
System.out.println("학점: C");
} else if (average >= 60) {
System.out.println("학점: D");
} else {
System.out.println("학점: F");
} // end else
System.out.println("\n프로그램 종료");
} // end main()
} // end class
4) com.lec.java.if04 패키지, If04Main 클래스
package com.lec.java.if04;
/* 삼항 연산자 (ternary operator)
* (조건식) ? 선택1 : 선택2
* (조건식)이 true 이면 선택1이 선택되고,
* (조건식)이 false 이면 선택2가 선택됨.
*/
public class If04Main {
public static void main(String[] args) {
System.out.println("if 문과 삼항 연산자");
// 두 숫자 중 누가 더 큰 숫자인가?
int num1 = 200;
//int num1 = 100;
int num2 = 123;
int big;
// if문을 이용하여 작성
// if(num1 > num2) {
// big = num1;
// } else {
// big = num2;
// }
// System.out.println("더 큰 수 : " + big);
// 삼항연산자를 이용하여 작성
big = num1 > num2 ? num1 : num2;
System.out.println("더 큰 수: " + big);
System.out.println();
// 두 수의 차(difference)
int num3 = 10;
int num4 = 20;
// int num3 = 20;
// int num4 = 10;
int diff;
// if문을 이용하여 작성하기
// if(num3 > num4) {
// diff = num3 - num4;
// } else {
// diff = num4 - num3;
// }
// System.out.println("두 수의 차 : " + diff);
// 삼항연산자를 이용하여 작성하기
diff = (num3 > num4) ? (num3 - num4) : (num4 - num3);
System.out.println("두 수의 차 : " + diff);
System.out.println("\n프로그램 종료");
} // end main()
} // end class
5) com.lec.java.if05 패키지, If05Main 클래스
package com.lec.java.if05;
/* 중첩된 if (nested-if) 문
* 조건문 안의 조건문
*/
public class If05Main {
public static void main(String[] args) {
System.out.println("중첩된 if (nested-if) 문");
int num = 97;
//int num = 98;
if(num % 2 == 0) {
System.out.println("짝수");
if(num % 4 == 0) {
System.out.println("4의 배수입니다!");
} else {
System.out.println("짝수이지만, 4의 배수는 아닙니다.");
}
} else {
System.out.println("홀수");
// 3의 배수이면 -> 3의 배수입니다.
// 3의 배수가 아니면 -> 홀수이지만, 3의 배수는 아닙니다.
if(num % 3 == 0) {
// 3의 배수
System.out.println("3의 배수입니다!");
} else {
System.out.println("홀수이지만, 3의 배수는 아닙니다.");
} // end 3 else
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
6) com.lec.java.if07 패키지, If07Main 클래스
package com.lec.java.if07;
/* String 비교, char 비교
* - 문자열 비교는 절대로 == 를 사용하지 말자
* - 문자열 비교는 equals(), equalsIgnoreCase() 사용!
*
* - char 는 기본적으로 정수값 (아스키 코드값) 이라 일반 산술 비교 가능
*/
public class If07Main {
public static void main(String[] args) {
System.out.println("String 비교, char 비교");
String str1 = "john";
String str2 = "john";
System.out.println("str1 = " + str1);
System.out.println("str2 = " + str2);
// 문법적인 에러는 아님
// 하지만 이렇게 실행하면 앙돼...ㅋ
// 참의 값이 나온다고 해서 낚이면 안돼
if(str1 == str2) {
System.out.println("== 같습니다.");
} else {
System.out.println("== 다릅니다.");
}
// 문자열 비교는 절대로 == 를 사용하지 말자
String str3 = "jo";
String str4 = str3 + "hn";
System.out.println("str4 = " + str4);
if(str1 == str4) {
System.out.println("== 같습니다.");
} else {
System.out.println("== 다릅니다.");
}
// 문자열 비교는 equals() 사용!
if(str1.equals(str4)) {
System.out.println("equals() 같습니다.");
} else {
System.out.println("equals() 다릅니다.");
}
String str5 = "John";
// equals()는 대소문자 구분
System.out.println(str1.equals(str5));
// equalsIgnoreCase()는 대소문자 구분 안 함
System.out.println(str1.equalsIgnoreCase(str5));
System.out.println();
// char 는 기본적으로 정수값 (아스키 코드값) 이라
// 일반 산술 비교가 가능.
char ch = '#';
//char ch = 'c';
//char ch = '7';
//char ch = 'R';
if('0' <= ch && ch <= '9') {
System.out.println("숫자입니다.");
} else if('A' <= ch && ch <= 'Z') {
System.out.println("대문자입니다.");
} else if('a' <= ch && ch <= 'z') {
System.out.println("소문자입니다.");
} else {
System.out.println("숫자도 알파벳도 아닙니다!");
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
** 문자열은 == 연산자를 사용하면 안된다!
** equals() 메소드를 사용해야 한다!
7) com.lec.java.if08 패키지, If08Main 클래스
package com.lec.java.if08;
/* 실수값은 정밀도(precision) 의 문제가 있기 때문에
* 산술계산 결과값 등의 '같은값 여부' 비교는 하지 말자
*/
public class If08Main {
public static void main(String[] args) {
System.out.println("실수 비교 연산");
float f1 = 0.01f;
float f2 = 0.1f * 0.1f;
System.out.println("f1 : " + f1);
System.out.println("f2 : " + f2);
if(f1 == f2) {
System.out.println("같습니다.");
} else {
System.out.println("다릅니다.");
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
2. Lec07_Switch
1) com.lec.java.switch01 패키지, Switch01Main 클래스
package com.lec.java.switch01;
/* switch - case 조건문
*
* switch (조건값){
* case 값1:
* ...
* case 값2:
* ...
* default:
* ...
* }
*
* 해당 조건의 case문을 찾아서 거기서부터 break를 만날 때까지 실행을 함.
* break를 만나게 되면 switch 문장을 종료.
* 해당하는 case가 없으면 default 문장을 실행함.
*
* ※ 모든 switch 조건문은 if - else if - else로 바꿀 수 있다. (할수 있어야 한다)
*/
public class Switch01Main {
public static void main(String[] args) {
System.out.println("switch 문");
int num = 3;
//int num = 3;
//int num = 2;
switch(num) {
case 1:
System.out.println("하나");
System.out.println("ONE");
break; //switch 안에서의 수행 종료.
case 2:
System.out.println("둘");
System.out.println("TWO");
break;
case 3:
System.out.println("셋");
System.out.println("THREE");
break;
default:
System.out.println("이도 저도 아님..");
}
System.out.println();
// break문이 없는 경우
// break문을 만날때 까지 계속 실행됨
int num2 = 1;
switch(num2) {
case 1:
System.out.println("하나");
System.out.println("ONE");
case 2:
System.out.println("둘");
System.out.println("TWO");
case 3:
System.out.println("셋");
System.out.println("THREE");
break;
default:
System.out.println("이도 저도 아님..");
}
System.out.println();
// 모든 switch 조건문 if - else if - else로 바꿀 수 있다.
if(num == 1) {
System.out.println("하나");
System.out.println("ONE");
} else if(num == 2) {
System.out.println("둘");
System.out.println("TWO");
} else if(num == 3) {
System.out.println("셋");
System.out.println("THREE");
} else {
System.out.println("이도 저도 아님..");
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
2) com.lec.java.switch02 패키지, Switch02Main 클래스
package com.lec.java.switch02;
public class Switch02Main {
public static void main(String[] args) {
System.out.println("switch 연습");
// 도전
// switch ~ case 조건문을 사용해서
// 짝수 이면 --> "짝수입니다" 출력
// 홀수 이면 --> "홀수입니다" 출력
int num = 99;
switch(num % 2) {
case 0: // 짝수
System.out.println("짝수입니다.");
break;
case 1: // 홀수
System.out.println("홀수입니다.");
} // end switch
System.out.println("\n프로그램 종료");
} // end main()
} // end class
3) com.lec.java.switch03 패키지, Switch03Main 클래스
package com.lec.java.switch03;
/* switch (조건) {case1: case2:}
* (조건)에 따라서 해당 case로 이동
* (조건)에 사용될 수 있는 자료 타입은
* 1. int로 변환 가능한 타입들: byte, short, int, char
* 2. enum 타입(enum 자료형은 Java 5 버전부터 소개)
* 3. String 타입 (Java 7 버전부터 switch 문에서 사용 가능)
*/
public class Switch03Main {
public static void main(String[] args) {
System.out.println("switch 제약 조건");
System.out.println("char를 switch문에서 사용");
char ch = 'C';
switch(ch) {
case 'a':
System.out.println('A');
break;
case 'b':
System.out.println('B');
break;
case 'c':
System.out.println('C');
break;
default:
System.out.println("몰라요~");
}
// 대소문자 구분 안하고 싶다.
// 그럼 case를 중첩시키면 됨
switch(ch) {
case 'a':
case 'A':
System.out.println('A');
break;
case 'b':
case 'B':
System.out.println('B');
break;
case 'c':
case 'C':
System.out.println('C');
break;
default:
System.out.println("몰라요~");
}
// switch(조건) 에 사용할수 없는 값들
long num = 1;
//switch(num) {} // 에러
// Cannot switch on a value of type long.
// Only convertible int values,
// string or enum variables are permitted
float real = 1;
//switch(real) {} // 에러
// Cannot switch on a value of type float.
// Only convertible int values,
// string or enum variables are permitted
System.out.println("\n프로그램 종료");
} // end main()
} // end class
4) com.lec.java.switch04 패키지, Switch04Main 클래스
package com.lec.java.switch04;
public class Switch04Main {
public static void main(String[] args) {
System.out.println("String 타입을 switch에서 사용하기");
// 문자열 비교 가능, 대신 대소문자 구분, 7버전부터 가능함
String language = "C++";
switch(language) {
case "Java":
System.out.println("Hello" + language);
break;
case "C++":
System.out.println("good bye C++");
break;
case "Swift":
System.out.println("Wow Swift");
break;
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
5) com.lec.java.switch05 패키지, Switch05Main 클래스
package com.lec.java.switch05;
public class Switch05Main {
// enum 타입 정의하는 방법:
// enum 이름 {}
// enum 타입 정의 메소드 안에서는 할 수 없다.
// enumeration 열거
// Days라는 enum 타입 선언
enum Days {SUN, MON, TUE, WED, THU, FRI, SAT};
public static void main(String[] args) {
System.out.println("enum 타입을 switch에서 사용하기");
Days day1 = Days.TUE;
System.out.println("day1 = " + day1);
Days day2 = Days.MON;
System.out.println("day2 = " + day2);
System.out.println();
System.out.println("day2를 switch문 값으로 넣음");
switch(day2) {
case SUN:
System.out.println("일요일");
break;
case MON:
System.out.println("월요일");
break;
case TUE:
System.out.println("화요일");
break;
case WED:
System.out.println("수요일");
break;
case THU:
System.out.println("목요일");
break;
case FRI:
System.out.println("금요일");
break;
case SAT:
System.out.println("토요일");
break;
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
3. Lec08_For
1) com.lec.java.for01 For01Main
package com.lec.java.for01;
/*
* ■ 순환문(loop)
* - for
* - while
* - do ~ while
*
* ■ for 순환문 구문
*
* for(①초기식; ②조건식; ④증감식){
* ③수행문;
* ..
* }
* ①초기식 : 최초에 단한번 수행
* ②조건식 : true / false 결과값
* 위 조건식의 결과가 false 이면 for문 종료
* ③수행문 : 위 조건식이 true 이면 수행
* ④증감식 : 수행문이 끝나면 증감식 수행
* 증감식이 끝나면 다시 ②조건식 으로..
*
* 순환문을 작성시 내가 만드는 순환문에 대해 다음을 확실하게 인지하고 작성해야 한다
* 1. 몇번 순환하는 가?
* 2. 순환중에 사용된 인덱스값의 시작값과 끝값은?
* 3. 순환문이 끝난뒤 인덱스값은?
*
*
for문 작성시 TIP
1) n번 순환 하는 경우 (즉 횟수가 촛점인 경우) 혹은 배열
for(int i = 0; i < n; i++){ .. }
2) a ~ b 까지 순환하는 경우 (즉 시작값과 끝값이 중요한 경우)
for(int i = a; i <= b; i++){ .. }
*/
public class For01Main {
public static void main(String[] args) {
System.out.println("for 반복문");
// 순환문이 없다면..??
// 수기로 계속 입력해줘야함, 매우 번거롭고 힘들다!!
System.out.println("Hello, Java1");
System.out.println("Hello, Java2");
System.out.println("Hello, Java3");
System.out.println();
// for문을 이용함으로 매우 간편해졌다!
for(int i = 1; i <= 3; i++) {
System.out.println("Hello, java" + i);
}
System.out.println();
for(int count = 1; count <= 10; count++) {
System.out.println("count : " + count);
}
System.out.println();
for(int k = 10; k > 0; k--) {
System.out.println("k = " + k);
}
System.out.println();
for(int k = 10; k >= 1; k--) {
System.out.println("k = " + k);
}
// 초기식과, 증감식에 식을 여러 개 사용 가능
System.out.println();
int i, j;
for(i = 0, j = 10; i < j; i++, j -= 2) {
System.out.println("i : " + i + " j : " + j);
}
System.out.println("for 종료 후\ni : " + i + " j : " + j);
System.out.println();
for(i = 0, j = 10; i < j; j -= 2) {
System.out.println("i : " + i + " j : " + j);
}
// 지역변수 : local variable
// 블럭 {...} 안에서 선언한 변수는
// 선언한 이후 그 블럭 안에서만 사용 가능.
// 블럭 끝나면 소멸됨.
System.out.println();
for(int k = 1; k % 27 != 0; k += 4) {
System.out.println("k = " + k);
}
// for 블럭 안에서 선언한 함수는 바깥에서 사용 불가
//System.out.println("for 종료 후 k = " + k); // 에러
// k cannot be resolved to a variable
{
int a = 100;
System.out.println("a = " + a);
{
// 안쪽의 블럭은 바깥쪽 블럭의 지역변수 사용 가능
// 바깥블럭 지역변수와 동일 이름의 변수 사용 불가
//int a = 200; // 에러
// Duplicate local variable a
int b = 200;
System.out.println(b);
}
// System.out.println("b = " + b); // 에러, 지역변수는 {...} 안에서만 유효함
// b cannot be resolved to a variable
}
// System.out.println("a = " + a); // 에러
System.out.println("프로그램 종료");
} // end main()
} // end class For01Main
2) com.lec.java.for02 패키지, For02Main 클래스
package com.lec.java.for02;
public class For02Main {
public static void main(String[] args) {
System.out.println("For문 - 구구단 출력");
// 구구단 2단
System.out.println();
for(int i = 1; i <= 9; i++) {
System.out.println("2 X " + i + " = " + (2 * i));
}
// 구구단 4단
System.out.println();
for(int i = 1; i <= 9; i++) {
System.out.println("4 X " + i + " = " + (4 * i));
}
// 2 x 2 = 4
// 3 x 3 = 9
//...
// 9 x 9 = 81
System.out.println();
for(int i = 2; i <= 9; i++) {
System.out.println(i + " x " + i + " = " + (i * i));
} // end for
System.out.println("\n프로그램 종료");
} // end main()
} // end class For02Main
3) com.lec.java.for03 패키지, For03Main 클래스
package com.lec.java.for03;
public class For03Main {
public static void main(String[] args) {
System.out.println("for 연습");
//1 ~ 10 수 중에서 짝수만 출력
for(int i = 1; i <= 10; i++) {
if(i % 2 == 0) {
System.out.println(i);
}
}
System.out.println();
for(int i = 2; i <= 10; i += 2) {
System.out.println(i);
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class For03Main
4) com.lec.java.for04 패키지, For04Main 클래스
package com.lec.java.for04;
public class For04Main {
public static void main(String[] args) {
System.out.println("for문 연습");
// 1 ~ 100 수 중에서 2와 7의 공배수만 출력
// 2와 7의 공배수 : 2의 배수 && 7의 배수
for(int i = 1; i <= 100; i++) {
if(i % 2 == 0 && i % 7 == 0) {
System.out.println(i);
}
}
// 1부터 10까지의 합을 계산
System.out.println("\n1 ~ 10까지 합");
int sum = 0; // 합계를 저장할 변수
for(int i = 1; i <= 10; i++) {
sum += i; // 누적 합산
}
System.out.println("sum = " + sum);
System.out.println("\n프로그램 종료");
} // end main ()
} // end class For04Main
4. Lec09_While
1) com.lec.java.while01 패키지, While01Main 클래스
package com.lec.java.while01;
/*
조건식이 true 인 동안 while 블럭 반복
while(조건식 true / false){
..
..
}
*/
public class While01Main {
public static void main(String[] args) {
System.out.println("while 반복문");
int count = 1; // 초기식
while(count <= 10) { // 조건식
System.out.println(count);
count++; // 증감식
} // end while
System.out.println();
count = 1; // 초기식
while(count <= 10) { // 조건식
count++; // 증감식
System.out.println(count);
} // end while
// 위의 두개의 while문을 통해 순서에 따라 결과값이 달라진다는 점을 알 수 있다..!!
// 이것이 바로 알고리즘이다~
System.out.println();
// 10, 9, 8, ..., 1까지 출력
count = 10; // 초기식
while(count >= 1) { //조건식
System.out.println(count);
count--; // 증감식
} // end while
System.out.println();
System.out.println("\n프로그램 종료");
} // end main()
} // end class While01Main
2) com.lec.java.while02 패키지, While02Main 클래스
package com.lec.java.while02;
public class While02Main {
public static void main(String[] args) {
System.out.println("while 연습");
// 구구단 2단
// while문 사용
int n = 1; // 초기식
while(n <= 9) { // 조건식
System.out.println("2 x " + n + " = " + (2 * n));
n++; // 증감식
} // end while
System.out.println("\n프로그램 종료");
} // end main()
} // end class While02Main
3) com.lec.java.while03 패키지, While03Main 클래스
package com.lec.java.while03;
public class While03Main {
public static void main(String[] args) {
System.out.println("while 연습");
// 1 ~ 10까지 수 중에서 홀수만 출력
int n = 1;
while (n <= 10) {
if (n % 2 == 1) {
System.out.println(n);
} // end if
n++;
} // end while
System.out.println("\nif 사용 안하기");
n = 1;
while (n <= 10) {
System.out.println(n);
n += 2;
} // end while
System.out.println("\n프로그램 종료");
} // end main()
} // end class While03Main
4) com.lec.java.dowhile 패키지, DoWhileMain 클래스
package com.lec.java.dowhile;
/*
do {
...
...
}while(조건식) 문인 경우에는,
{...} 안에 있는 실행문들을 한번은 실행을 하고 나서
조건식을 검사하게 된다.
*/
public class DoWhileMain {
public static void main(String[] args) {
System.out.println("while문 연습");
int n = 0;
while(n > 0) {
// 조건이 false이기 때문에 한 번도 실행 안한다
System.out.println("카운트다운(while) : " + n);
n--;
}
n = 0;
do {
// 조건이 false라도 무조건 한 번 실행
System.out.println("카운트다운(do~while) : " + n);
n--;
} while(n > 0);
// 구구단 9단을 do~while로 출력
System.out.println();
int num = 1;
do {
System.out.println("9 x " + num + " = " + (9 * num));
num++;
} while (num <= 9);
System.out.println("\n프로그램 종료");
} // end main()
} // end class While04Main
5. Lec10_Loop
1) com.lec.java.loop01 패키지, Loop01Main 클래스
package com.lec.java.loop01;
/* break;
* 순환문(for, while, do~while) 안에서 break를 만나면
* break를 감싸는 가장 가까운 순환문 종료
*/
public class Loop01Main {
public static void main(String[] args) {
System.out.println("Break");
int num = 1;
while(num <= 10) {
System.out.println(num);
if(num == 3) {break;}
num++;
} // end while
System.out.println();
// 2와 7의 최소공배수를 출력
// 최소공배수: 공배수 중에서 가장 작은 수
int a = 2, b = 7;
int start = (a > b)? a : b;
while(true) { // 안끝나는 무한루프(무한반복)
if(start % 2 == 0 && start % b == 0) {
System.out.println("2와 7의 최소공배수 : " + start);
break;
}
start++;
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
2) com.lec.java.loop02 패키지, Loop02Main 클래스
package com.lec.java.loop02;
/* continue;
* 순환문(for, while, do~while) 안에서 continue 를 만나면
* continue를 감싸는 가장 가까운 순환문 으로 돌아감
*/
public class Loop02Main {
public static void main(String[] args) {
System.out.println("continue;");
int num = 0;
while(num <= 10) {
num++;
if(num % 2 == 0) {
continue;
}
System.out.println(num);
}
System.out.println();
// for문과 continue를 사용해서
// 1 ~ 10 숫자 중 짝수만 출력
for(num = 1; num <= 10; num++) {
if(num % 2 == 0) {
continue;
}
System.out.println(num);
} // end for
System.out.println("\n프로그램 종료");
} // end main()
} // end class
3) com.lec.java.loop03 패키지, Loop03Main 클래스
package com.lec.java.loop03;
public class Loop03Main {
public static void main(String[] args) {
System.out.println("중첩 for 문 nested for");
// 구구단 출력 : 중첩 for 사용
// for(int dan = 2; dan <= 9; dan++) {
// System.out.println(dan + "단");
// for(int n = 1; n <= 9; n++) {
// System.out.println(dan + " x " + n + " = " + (dan * n));
// }
// System.out.println();
// }
System.out.println();
// 구구단 출력 : 중첩 while 문 사용
int dan = 2;
while(dan <= 9) {
System.out.println("구구단 " + dan + "단");
int n = 1;
while(n <= 9) {
System.out.println(dan + " x " + n + " = " + (dan * n));
n++;
}
System.out.println();
dan++;
}
System.out.println("\n프로그램 종료");
} // end main()
} // end class
'웹_프론트_백엔드 > JAVA프레임윅기반_풀스택' 카테고리의 다른 글
2020.03.20 (0) | 2020.03.20 |
---|---|
2020.03.19 (0) | 2020.03.19 |
2020.03.17 (0) | 2020.03.17 |
2020.03.16 (0) | 2020.03.16 |
학습목표 및 일정(3월 16일 ~ 8월 06일) (0) | 2020.03.16 |