"String format".contains(CharSequence s)
- 앞의 문자열이 s를 포함하면 true
public class Main {
public static void main(String[] args) {
String a = "I love you.";
if(a.contains("love"))
{
System.out.println("Me too");
}
else
{
System.out.println("I hate you");
}
}
}
Me too
"String".equals(Object anotherObject)
- 앞의 문자열과 뒤의 문자열이 같으면 true
"String".equalsIgnoreCase(String anotherString)
- compares two strings, ignoring lower case and upper case differences.
대소문자 상관없이 비교- 같으면 true
public class Main {
public static void main(String[] args) {
String a = "Man";
int b = 0;
if(a.equals("Man"))
{
System.out.println("남자입니다.");
}
else
{
System.out.println("남자가 아닙니다.");
}
if(b == 3)
{
System.out.println("b는 3입니다.");
}
else
{
System.out.println("3이 아닙니다.");
}
if(a.equalsIgnoreCase("man") && b == 0)
{
System.out.println("참입니다.");
}
else
{
System.out.println("거짓입니다.");
}
}
}
남자입니다.
3이 아닙니다.
참입니다.
import java.util.Scanner;
public class Ex4_04 {
public static void main(String[] args) {
//점수와 학점
int score = 0; //점수
char grade = 'F'; //학점, 띄어쓰기로 초기화!!!!! 공백 안됨!!!
//중요!! 아예 처음부터 마지막 조건으로 초기화하면 마지막 조건은 생략가능!!
System.out.println("점수를 입력하세요.");
Scanner scan = new Scanner(System.in);
score = scan.nextInt();
if(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+"'입니다.");
scan.close();
}
}
점수를 입력하세요.
59
학점은 'F'입니다.
import java.util.Scanner;
public class Ex4_05 {
public static void main(String[] args) {
//중첩if 사용하여 학점을 더 세분화하기
int score = 0;
char grade = 'C'; //이것도 마찬가지로!
char opt = '0'; //어찌보면 이것도
System.out.println("당신의 점수를 입력하세요.");
Scanner scan = new Scanner(System.in);
score = scan.nextInt();
if(score >= 90) {
grade = 'A';
if(score >= 98) {
opt = '+';
}
else if(score < 94) {
opt = '-';
}
} else if(score >= 80) {
grade = 'B';
if(score >= 88) {
opt = '+';
}
else if(score < 84) {
opt = '-';
}
}
System.out.printf("당신의 점수는 %d, 학점은 '%c%c'입니다.", score, grade, opt);
scan.close();
}
}
당신의 점수를 입력하세요.
79
당신의 점수는 79, 학점은 'C0'입니다.
switch (조건식) {
case 값1 :
//조건식의 결과가 값1과 같을 경우 수행될 문장들
//...
break;
case 값2 :
//...
//...
break;
//...
//...
default :
//조건식의 결과와 일치하는 case문이 없을 때 수행될 문장들
//...
}
1) 조건식을 계산한다. -> ✨정수나 문자열✨
2) 조건식의 결과와 일치하는 case
문으로 간다. 일치하는 case
문이 없을 경우 default
로 간다.
dafault
는 생략가능하다.3) 이후의 문장들을 실행한다.
4) break
문이나 switch
문의 끝을 만나면 switch문 전체를 빠져나간다.
1) switch
문의 조건식 결과는 ✨정수 또는 문자열✨이어야 한다.
2) case
문의 값은 ✨정수 💖상수(문자 포함), 문자열✨만 가능하다.
- ✨변수 안됨!!!
break
가 없다면?다음 break
를 만날 때까지 또는 switch
문이 끝날 때까지 계속 수행한다.
import java.util.Scanner;
public class Ex4_06 {
public static void main(String[] args) {
// switch로 계절
System.out.print("현재의 월을 입력하세요. : ");
Scanner scanner = new Scanner(System.in);
int month = scanner.nextInt();
switch (month) {
case 3:
case 4:
case 5:
System.out.println("봄"); //이렇게 세 줄로 할 수도 있고
break;
case 6: case 7: case 8: //한번에 한 줄로 할 수도 있고
System.out.println("여름");
break;
case 9: case 10: case 11:
System.out.println("가을");
break;
default:
System.out.println("겨울");
}
scanner.close();
}
}
현재의 월을 입력하세요. : 1
겨울
public class Main {
public static void main(String[] args) {
int i = 1, sum = 0;
while(i <= 1000)
{
sum += i++;
}
System.out.println("1부터 1000까지의 합은 " + sum + "입니다.");
}
}
i = 1 이므로 <= 1000 (true) -> while 안으로
sum = (현재sum=)0 + (현재i=)1 -> sum = 1
sum 줄을 빠져나가면 i = 2 가 됨
이 i는 <= 1000 (true) -> 다시 while 안으로
sum = (현재sum=)1 + (현재i=)2 -> sum = 3
sum 줄을 빠져나가면 i = 3 가 됨
...
i = 1000 이므로 <= 1000 (true) -> 다시 while 안으로
sum = (현재sum=)499500 + (현재i=)1000 -> sum = 500500
sum 줄을 빠져나가면 i = 1001 가 됨
이젠 i > 1000 -> while 밖으로 빠져나감
-> println 실행, 현재 sum = 500500
-> "1부터 1000까지의 합은 500500입니다."
1부터 1000까지의 합은 500500입니다.
for
for(1초기화, 2조건, 4연산) { // 3조건이 true면 실행 }
- 1 -> (2 -> 3 -> 4 -> 2)반복
- 각각은 생략가능
- 조건식이 생략되면
true
-> 무한반복
반복횟수를 알 때
✨for
문 안에서 선언된 변수는 밖에서 사용할 수 없다!!
변수의 범위scope는 선언된 순간의 위치부터 선언된 블록의 끝까지 이므로
사용하고 싶다면 그 앞에 미리 선언하기!
for(int i=1; i<=10; i++) {
System.out.print(i+" ");
}
1 2 3 4 5 6 7 8 9 10
이런 식으로 하면 알 수 있다!!
public class Ex4_10 {
public static void main(String[] args) {
//반복문을 이용하여 1~5의 합 구하기
int sum = 0;
int i = 1;
for(; i<=5; i++) {
sum += i;
System.out.printf("1부터 %2d의 합은 : %2d%n", i, sum);
//%2d는 두자리의 십진수
}
System.out.printf("총 1부터 %2d의 합은 : %2d%n", --i, sum);
//i--하면 이 다음부터 수행되므로 5가 아니라 6이 나온다.
}
}
1부터 1의 합은 : 1
1부터 2의 합은 : 3
1부터 3의 합은 : 6
1부터 4의 합은 : 10
1부터 5의 합은 : 15
총 1부터 5의 합은 : 15
public class Ex4_11 {
public static void main(String[] args) {
// 구구단!
for(int i=2; i<10; i++) {
for(int j=1; j<10; j++) {
System.out.printf("%d*%d = %d%n", i, j, i*j);
}
System.out.println();
}
}
}
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
public class Main {
final static int N = 10;
public static void main(String[] args) {
for(int i = N; i > 0; i--)
{
for(int j = i; j > 0; j--)
{
System.out.print("*");
}
System.out.println();
}
}
**********
*********
********
*******
******
*****
****
***
**
*
public class Main {
final static int N = 10;
public static void main(String[] args) {
// 원의 중심이 (0, 0)일 때, 원의 임의의 점 (x, y)일 때,
// 원의 방정식 x^2 + y^2 = r^2
for(int i = -N; i <= N; i++)
{
for(int j = -N; j <= N; j++)
{
if(i * i + j * j <= N * N)
{
System.out.print("*");
}
else
{
System.out.print(".");
}
}
System.out.println();
}
}
}
..........*..........
......*********......
....*************....
...***************...
..*****************..
..*****************..
.*******************.
.*******************.
.*******************.
.*******************.
*********************
.*******************.
.*******************.
.*******************.
.*******************.
..*****************..
..*****************..
...***************...
....*************....
......*********......
..........*..........
Sample07
package kr.or.test;
import java.util.Scanner;
public class Sample07 {
public static void main(String[] args) {
/*
for문을 이용하고 3항연산자를 이용해서
아래와 같은 코드를 완성하시오.
정수를 입력하세요
5
0 + 1 + 2 + 3 + 4 + 5 = 15
*/
System.out.println("정수를 입력하세요.");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
for(int i=0; i<=n; i++) {
System.out.print(i);
sum += i;
if(i != n) {
System.out.print(" + ");
}
}
System.out.println(" = "+sum);
scan.close();
}
}
정수를 입력하세요.
7
0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28
Sample08
package kr.or.test;
import java.util.Scanner;
public class Sample08 {
public static void main(String[] args) {
/*
* 3항연산자를 이용해서 작성하시오
짝수를 출력하는 내용과 같게 작성하시오.
3항연산자를 이용해서 작성하시오
for문을 이용해서 작성하시오
정수를입력하세요
5
0 + 2 + 4 = 6
*/
System.out.println("정수를 입력하세요.");
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int sum = 0;
for(int i=0; i<=n; i++) {
if(i%2==0) {
System.out.print(i);
sum += i;
} else if(i!=n) {
System.out.print(" + ");
}
}
System.out.println(" = "+sum);
scan.close();
}
}
정수를 입력하세요.
7
0 + 2 + 4 + 6 = 12
while
int i = 5; //반복할 횟수!!
while(i-- != 0) {
System.out.println(i+" - i can do it");
}
4 - i can do it
3 - i can do it
2 - i can do it
1 - i can do it
0 - i can do it
public class Ex4_13 {
public static void main(String[] args) {
//100을 안넘게
int i=0;
int sum=0;
while(sum<=100) {
System.out.printf("%d - %d%n", i, sum);
sum += ++i;
// i++;
// sum += i; //이렇게 할 수도 있다!
}
}
}
0 - 0
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
import java.util.Scanner;
public class Ex4_14 {
public static void main(String[] args) {
//입력받은 각 자릿수의 합
//'%10'-> 마지막 자리를 얻는다.
//예) 12345%10 -> 5
int sum=0;
System.out.print("정수를 입력하세요. (예: 12345) : ");
Scanner scan = new Scanner(System.in);
int num = scan.nextInt();
//12345, 1234, 123, 12, 1 을 뽑아낸다!!
for(; num>0; num /= 10) { //생각해내기 너무 어렵다.
System.out.println(num);
sum += num%10;
}
System.out.println("각 자릿수의 합은? : "+sum);
scan.close();
}
}
정수를 입력하세요. (예: 12345) : 12345
12345
1234
123
12
1
각 자릿수의 합은? : 15
do-while
do { //조건식의 연산결과가 참일 때 수행될 문장 //한번은 무조건 실행!! } while(조건식);
- 블럭
{}
을 최소 한 번 이상 반복(1~n번)- 사용자 입력을 받을 때 유용
while
끝에 ✨;
를 빼먹지 말자!!
import java.util.Scanner;
public class Ex4_15 {
public static void main(String[] args) {
// 1이상~100이하 랜덤숫자를 맞히기
System.out.println("1~100 사이의 정수를 맞히시오.");
int answer = (int) (Math.random()*100) + 1;
System.out.println("Answer : "+answer);
System.out.print("입력하시오. : ");
Scanner scan = new Scanner(System.in);
int num;
do {
num = scan.nextInt();
if (num>answer) {
System.out.println("더 작은 수로 시도해 보세요.");
} else if(num<answer){ //else if 다!!
System.out.println("더 큰 수로 시도해 보세요.");
}
} while(num != answer);
// num = scan.nextInt(); //while로 하면 한번 더 써야 하므로
scan.close();
System.out.println("정답입니다.");
}
}
1~100 사이의 정수를 맞히시오.
Answer : 5
입력하시오. : 20
더 작은 수로 시도해 보세요.
10
더 작은 수로 시도해 보세요.
6
더 작은 수로 시도해 보세요.
7
더 작은 수로 시도해 보세요.
5
정답입니다.
break
break;
break;
를 넣는다.for(;;)
& while(true)
public class Main {
public static void main(String[] args) {
int count = 0;
for(;;)
{
System.out.println("출력");
count++;
if(count == 10)
{
break;
}
}
}
}
출력
출력
출력
출력
출력
출력
출력
출력
출력
출력
continue;
자신이 포함된 반복문의 끝으로 이동해 4연산으로(다음반복으로) 넘어감
전체 반복 중에서 특정 조건 시 반복을 건너뛸 때 유용
public class Ex4_17 {
public static void main(String[] args) {
// continue, 2의 배수만 건너뛰기
for(int i=0; i<=10; i++) {
if(i%2 == 0)
continue;
System.out.println(i);
}
}
}
1
3
5
7
9
import java.util.Scanner;
public class Ex4_18 {
public static void main(String[] args) {
// continue, break, 메뉴 선택하기
Scanner scan = new Scanner(System.in);
while(true) {
System.out.println("(1) 짜장");
System.out.println("(2) 짬뽕");
System.out.println("(3) 탕수육");
System.out.print("메뉴를 선택하세요.(0 : 종료) > ");
String tmp = scan.nextLine();
int menu = Integer.parseInt(tmp);
//문자열을 받아 숫자로
if(menu == 0) {
System.out.println("프로그램을 종료합니다.");
break;
}
else if(!(1<=menu && menu <= 3)){
System.out.println("메뉴를 잘못 선택하셨습니다.");
continue;
//다음 반복문으로 -> 다시 (1),(2)...메뉴선택하세요
}
System.out.println(menu+"번 메뉴를 선택하셨습니다.");
}
scan.close();
}
}
(1) 짜장
(2) 짬뽕
(3) 탕수육
메뉴를 선택하세요.(0 : 종료) > 5
메뉴를 잘못 선택하셨습니다.
(1) 짜장
(2) 짬뽕
(3) 탕수육
메뉴를 선택하세요.(0 : 종료) > 2
2번을 선택하셨습니다.
(1) 짜장
(2) 짬뽕
(3) 탕수육
메뉴를 선택하세요.(0 : 종료) > 0
프로그램을 종료합니다.
이름 : for() {
//...
if() {
break 이름;
}
//...
}