현재 디렉토리

 

1. 먼저 myutil 패키지 안에 myInfo클래스를 형성하고, 메소드를 작성했다.

-- 메서드 앞 public 접근제어자 : 어디서든 이 메서드 접근 가능

-- 메서드 앞 static 제어자 없음 : 인스턴스 형성 후 이 메서드 사용 가능

package myutil;

import java.util.Calendar;

public class MyInfo {
	
	//1. 띠 구하기
	//십이지 : 신유술해자축인묘진사오미 (0~11) 
	//식 : (현재년도 % 12)번째 십이지 (입 : int year, 출 : String)
	public String getTti(int year) {
		String[] Tti = {"원숭이", "닭", "개", "돼지","쥐", "소", "호랑이", 
		        "토끼","용","뱀", "말", "양",};
		int n = year % 12;
		return Tti[n];
	}
	
	//2. 간지 구하기
	//간지 : 경신임계갑을병정무기(0~9)
	//십이지 : 신유술해자축인묘진사오미 (0~11)
	//식 : (현재년도 % 10)번째 간지 + (현재년도 %12)번째 십이지 (입 : int year, 출 : String)
	public String getGanji(int year) {
		String[] Ganji = {"경","신","임","계","갑","을","병","정","무","기"};
		String[] Tti = {"신","유","술","해","자","축","인","묘","진","사","오","미"};
		int g = year % 10;
		int t = year % 12;
		
		return Ganji[g]+Tti[t];
	}
	
	
	//3. 출생년도로부터 나이 구하기 (입 : int year, 출 : int age)
	//   식 : 현재년도 - 출생년도 + 1
	public int getAge(int year) {
		//현재 년도
		Calendar c = Calendar.getInstance();
		int current_year = c.get(Calendar.YEAR);
		
		//식
		int age = current_year - year + 1;
		return age;
	}
}

 

2. mymain.Main1.java의 메인 함수에서 출력을 했다.

package mymain;

import java.util.Calendar;
import java.util.Scanner;

import myutil.MyInfo;

public class Main1 {

	public static void main(String[] args) {
		//출생년도를 통해 올해 띠, 간지, 나의 나이 구하기
		
		Scanner scanner = new Scanner(System.in);
		MyInfo myinfo = new MyInfo();
		Calendar c = Calendar.getInstance();
		
		System.out.print("당신의 출생년도를 입력하세요(ex.1994) : ");
		int user_year = scanner.nextInt();
		
		int current_year = c.get(Calendar.YEAR);
		
		System.out.printf("올해는 %d이며 %s의 해입니다.%n",current_year,myinfo.getTti(current_year));
		System.out.printf("올해는 %d이며 %s년입니다.%n",current_year,myinfo.getGanji(current_year));
		System.out.printf("올해는 %d이며 당신은 %d살이 되었습니다.%n",current_year,myinfo.getAge(user_year));
		
		scanner.close();
	}

}

>> 결과

당신의 출생년도를 입력하세요(ex.1994) : 1400
올해는 2022이며 호랑이의 해입니다.
올해는 2022이며 임인년입니다.
올해는 2022이며 당신은 623살이 되었습니다.

1. 최대값을 구하기

 

[1] 세 개의 양수 중 최대값 구하기

package practice2_Q;

import java.util.Scanner;

public class Q1 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int[] arr = new int[3];
		System.out.print("세 개의 양수를 입력하세요 : ");
		arr[0] = scanner.nextInt();
		arr[1] = scanner.nextInt();
		arr[2] = scanner.nextInt();
		
		int max = 0;
		
		for(int i = 0; i < 3; i++) {
			if(max <= arr[i]) {
				max = arr[i];
			}
		}
		System.out.println("Max : "+max);
		
		scanner.close();
	}

}

>> 결과

세 개의 양수를 입력하세요 : 5 89 21
Max : 89

 

 

2. 입력받은 문자 읽기

 

[1] 사용자가 입력한 문자에서 알파벳 문자, 숫자, 화이트문자, 특수문자 갯수 출력

package practice2_Q;

import java.io.IOException;

public class Q2 {

	public static void main(String[] args) throws IOException{
		int ch = 0;
		int[] cnt = {0, 0, 0, 0}; //알파벳, 숫자, 화이트, 특수문자 순차 입력
		
		System.out.println("문자를 입력하세요(Ctrl+z하면 완료)");
		do
		{
			ch = System.in.read();
			
			if(ch == -1) break;
			
			System.out.printf("%c",ch);
			
			if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) {
				cnt[0]++; //알파벳
			}else if(ch >= '0' && ch <= '9') {
				cnt[1]++; //숫자
			}else if(ch == '\r' || ch == '\n' || ch == ' ' || ch == '\t'){
				cnt[2]++; //화이트문자
			}else {
				cnt[3]++; //기타(특수기호)
			}
		}while(true);
		System.out.println();
		System.out.println("알파벳   : "+cnt[0]);
		System.out.println("숫자     : "+cnt[1]);
		System.out.println("화이트   : "+cnt[2]);
		System.out.println("특수문자 : "+cnt[3]);	

	}

	
}

>> 결과

문자를 입력하세요(Ctrl+z하면 완료)
hey there, wanna hang out? :)
hey there, wanna hang out? :)

알파벳   : 20
숫자     : 0
화이트   : 7
특수문자 : 4

 

[2] 사용자로부터 두 개의 양수와 연산자를 받아 계산하기 

package practice2_Q;

import java.util.Scanner;

public class Q3 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("두 개의 양수와 연산자를 입력하세요 : ");
		int x = scanner.nextInt();
		int y = scanner.nextInt();
		String z = scanner.next();
		int result = 0;
		
		switch(z){
			case "+" : result = x + y; break;
			case "-" : result = x - y; break;
			case "*" : result = x * y; break;
			case "/" : result = x / y; break;
			case "%" : result = x % y; break;
			default  : result = -1;
		}
		System.out.printf("%d %s %d = %d",x,z,y,result);
		
		scanner.close();
	}

}

>> 결과

두 개의 양수와 연산자를 입력하세요 : 2 3 +
2 + 3 = 5

 

[3] 사용자로부터 알파벳 문자를 하나 받아 나라명 출력하기 (if - else문 활용)

package practice2_Q;

import java.io.IOException;

public class Q4 {

	public static void main(String[] args) throws IOException {
		String[] nation = {"America","Bangladesh", "Canada", "Demmark","Ezypt", "France", 
				"Greece","Hungary","Iceland","Jamaica","Korea",
				"Lebanon","Malta","North Korea","Oman","Peru","Qatar","Romania","Singapore",
				"Thailand","Uganda","Vietnam","W로 시작하는 나라는 없습니다.","X로 시작하는 나라는 없습니다.","Yemen","Zambia"};
		String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		
		System.out.print("문자 한 개를 입력하세요. >> ");
		int ch = System.in.read();
		
		//소문자 -> 대문자
		if(ch >= 'a' || ch <= 'z') ch -= 32;

		for(int i = 0; i < alpha.length(); i++) {
			if(ch == alpha.charAt(i)) {
				System.out.printf("%c로 시작하는 나라는 : %s",ch,nation[i]);
			}
		}
	}

}

>> 결과

문자 한 개를 입력하세요. >> a
A로 시작하는 나라는 : America

 

3. 사칙연산 결과를 테이블 형식으로 출력 

 

[1] 정상가격과 세일가격(30%) 출력하기 (정상가격 범위 : 20000원~30000원)

package practice2_Q;

public class Q5 {

	public static void main(String[] args) {
		System.out.println("정상가격      세일가격");
		System.out.println("--------------------------");//14
		
		for(int price = 20000; price <= 30000; price+=1000) {
			System.out.printf("%-13d %.0f\n",price,price*0.7);
		}
	}

}

>> 결과

 

정상가격      세일가격
--------------------------
20000         14000
21000         14700
22000         15400
23000         16100
24000         16800
25000         17500
26000         18200
27000         18900
28000         19600
29000         20300
30000         21000

 

[2] 사용자에게 양의 정수 n을 받아, 1부터 n까지 합 구하기 

package practice2_Q;

import java.util.Scanner;

public class Q6 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("양수 n : ");
		int n = scanner.nextInt();
		int sum = 0;
		
		for(int i = 1; i <= n; i++) {
			sum += i;
		}
		System.out.println("sum : "+sum);
		
		scanner.close();
	}

}

>> 결과

양수 n : 5
sum : 15

 

[3] 1부터 10까지 양의 정수 중 짝수의 곱을 구하기

package practice2_Q;

public class Q7 {

	public static void main(String[] args) {
		int n = 10;
		int result = 1;
		
		for(int i = 1; i <= n; i++) {
			if(i % 2 == 0)
				result = result * i;
		}
		System.out.println("result : "+result);
	}

}

>> 결과

result : 3840

 

[4] 원주율을 구하는 공식에 따라 원주율 값 구하기

4/1 - 4/3 + 4/5 - 4/7 + 4/9 .....
package practice2_Q;

public class Q8 {
	public static void main(String[] args) {
		int n = 1;
		int sign = 1;
		double result = 0;
		for(long i = 0; i < 2000000000; i++) {
			result += sign*(4.0/n);
			sign = -sign;
			n += 2;
		}
		System.out.println("PI = "+result);
	}
}

>> 결과

PI = 3.141592658505181

 

4. 제곱과 팩토리얼

 

[1] (제곱) 0~6까지의 제곱과 세제곱을 구하여 테이블 형식으로 출력

package practice2_Q;

public class Q9 {

	public static void main(String[] args) {
		System.out.println("기존      제곱      세제곱");
		System.out.println("-----------------------------");
		
		for(int i = 0; i < 7; i++) {
			System.out.printf("%-10d%-10d%d%n",i,i*i,i*i*i);
		}
	}

}

>> 결과

기존      제곱      세제곱
-----------------------------
0         0         0
1         1         1
2         4         8
3         9         27
4         16        64
5         25        125
6         36        216

 

[2] (팩토리얼) 사용자에게 양의 정수 n을 받아, n! 구하기 (n! = n * (n-1)! // 단, 0!은 1이다)

package practice2_Q;

import java.util.Scanner;

public class Q10 {

	public static void main(String[] args) {
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("n값 : ");
		long n = scanner.nextInt();
		long result = 1;
		
		//f(x) = x * f(x-1) 
		//단, x가 0일 때 값은 1이다.
		if(n == 0) {
			result = 1;
		}else {
			for(long i = n; i > 0; i--) {
				result = result * i; 
			}
		}
		System.out.printf("%d! = %d",n,result);

		scanner.close();
	}
	
}

>> 결과

n값 : 3
3! = 6

 

[※ 참고 : 팩토리얼 원리]
- 팩토리얼이란 무엇일까? https://johnleeedu.tistory.com/23
- 팩토리얼을 왜 사용하나?
  https://ko.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/the-factorial-function
- 팩토리얼의 수학 원리 https://www.youtube.com/watch?v=zSUMcsASTTo 

팩토리얼은 고등수학에서 순열과 조합을 배우면서 배우는 것인데, 경우의 수를 구할 때 사용한다.
원리는 다음과 같다.
만약 A,B,C 세 사람이 앉는 순서를 정한다 할 때 경우의 수는 아래처럼 구할 수 있다.

0!이 1인 이유는, 아무것도 없을 때에 "없다"는 것도 하나의 경우에 해당하기 때문

 

[3] 실수의 거듭 제곱 값 구하기 (실수 : r, 정수 : n)

package practice2_Q;

import java.util.Scanner;

public class Q11 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		System.out.println("실수, 정수를 하나씩 입력하세요.(ex.5.34 7)");
		double r = scanner.nextDouble();
		int n = scanner.nextInt();
		double result = 1;
		
		for(int i = 0; i < n; i++) {
			result = result * r;
		}
		System.out.printf("%f^%d = %f",r,n,result);
		
		scanner.close();
	}
}

>> 결과

실수, 정수를 하나씩 입력하세요.(ex.5.34 7)
5.231    3
5.231000^3 = 143.137741

구구단/행렬/별찍기 모두 원리는 비슷했다. 

결국 수학의 (x , y) 행렬이라 볼 수 있는데, 중첩 for문을 사용해서 구현이 가능하다.

------------------------------------------------------------------------------------------------------------------- 

 

1. 구구단 예제

 

[1] 구구단 2~9단을 출력하라_중첩 for문 활용

package practice;

public class dan99TestBasic {

	public static void main(String[] args) {
		for(int i = 2; i <= 9; i++) {
			System.out.println("--------["+i+"단 시작]--------");
			for(int j = 1; j <= 9; j++) {
				System.out.printf("%d x %d = %2d%n",i,j,i*j);
			}
		}
	}

}

>> 결과

--------[2단 시작]--------
2 x 1 =  2
2 x 2 =  4
2 x 3 =  6
2 x 4 =  8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
--------[3단 시작]--------
3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
--------[4단 시작]--------
4 x 1 =  4
4 x 2 =  8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
--------[5단 시작]--------
5 x 1 =  5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
--------[6단 시작]--------
6 x 1 =  6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
--------[7단 시작]--------
7 x 1 =  7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
--------[8단 시작]--------
8 x 1 =  8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
8 x 6 = 48
8 x 7 = 56
8 x 8 = 64
8 x 9 = 72
--------[9단 시작]--------
9 x 1 =  9
9 x 2 = 18
9 x 3 = 27
9 x 4 = 36
9 x 5 = 45
9 x 6 = 54
9 x 7 = 63
9 x 8 = 72
9 x 9 = 81

 

[1-2] 사용자가 입력한 x단의 구구단을 출력하라_do_while 활용

(단, 사용자는 여러 번 구구단을 입력하고 결과를 받을 수 있어야 한다.)

package practice;

import java.util.Scanner;

public class Dan99Test2 {

	public static void main(String[] args) {
				
		int dan = 0;
		String yn = "Y";
		Scanner scanner = new Scanner(System.in);
		
		do
		{
			System.out.print("단 입력(2~9단 중 하나) : ");
			dan = scanner.nextInt();
			
			if(dan >= 2 && dan <= 9) {
				for(int i = 1; i <=9; i++) {
					System.out.printf("%d x %d = %2d\n",dan,i,dan*i);
				}
				System.out.print("더 하시겠습니까? (y/n) :");
				yn = scanner.next();
			}else {
				System.out.println("2~9 중 하나를 입력해주세요.");
			}
		}while(yn.equals("Y") || yn.equals("y"));
			
		scanner.close();
	}

}

>> 결과

단 입력(2~9단 중 하나) : 3
3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
더 하시겠습니까? (y/n) :n

 

2. 행렬

 

[1] 아래와 같은 형태의 행렬을 출력하라.

>> 결과1

(1,1) (1,2) (1,3) (1,4) (1,5) 
(2,1) (2,2) (2,3) (2,4) (2,5) 
(3,1) (3,2) (3,3) (3,4) (3,5) 
(4,1) (4,2) (4,3) (4,4) (4,5) 
(5,1) (5,2) (5,3) (5,4) (5,5)

 

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {
		//중첩for문_행렬 구하기
		int row = 5;
		int col = 5;
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				System.out.printf("(%d,%d) ",i, j);
			}
			System.out.println();
		}
	}

}

 

[2] 아래와 같이 좌->우로 내려오는 대각선에 공백을 둔 행렬을 출력하라

>> 결과

( , ) (1,2) (1,3) (1,4) (1,5) 
(2,1) ( , ) (2,3) (2,4) (2,5) 
(3,1) (3,2) ( , ) (3,4) (3,5) 
(4,1) (4,2) (4,3) ( , ) (4,5) 
(5,1) (5,2) (5,3) (5,4) ( , )

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {	
		//중첩for문+continue_행렬에서 i==j값 공백
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				if(i == j) {
					System.out.printf("( , ) ",i, j);
					continue;
				} 
				System.out.printf("(%d,%d) ",i, j);
			}
			System.out.println();
		}
	}

}

 

[3] 아래와 같이 좌->우로 내려오는 대각선에 공백을 두고, 대각선의 우측은 제외하여 출력하라.

>> 결과

( , ) 
(2,1) ( , ) 
(3,1) (3,2) ( , ) 
(4,1) (4,2) (4,3) ( , ) 
(5,1) (5,2) (5,3) (5,4) ( , )

>> 소스코드

package practice;

public class MatrixTest {

	public static void main(String[] args) {
		//중첩for문+continue label_행렬에서 i==j값 공백, i<j면 미출력
		OUT_FOR : 
		for(int i = 1; i <= row; i++) {
			for(int j = 1; j <= col; j++) {
				if(i == j) {
					System.out.printf("( , ) ",i, j);
					continue;
				}else if(i < j) {
					System.out.println();
					continue OUT_FOR;
				}else {
					System.out.printf("(%d,%d) ",i, j);
				}
			}
			System.out.println();
		}
	}

}

 

3. 별찍기

 

 [1] 정사각형 별찍기

package practice;

public class StarTest1 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

}

>> 결과

*****
*****
*****
*****
*****

 

[2] 반피라미드 - 좌->우 대각선 하위만 출력

package practice;

public class StarTest2 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(j <= i) {
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

*
**
***
****
*****

 

[3] 역 반피라미드 - 좌->우 대각선 상위만 출력

package practice;

public class StarTest3 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(j >= i) {
					System.out.print("*");
				}else {
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

*****
 ****
  ***
   **
    *

 

[4] 바람개비 - 좌->우, 우->좌 대각선 제외 출력 

package practice;

public class StarTest4 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				if(i == j || 4-j==i) {
					System.out.print(" ");
				}else {
					System.out.print("*");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

 *** 
* * *
** **
* * *
 ***

 

[4-2] 반피라미드 - 우->좌 대각선 하위만 출력 (그림에 이걸 빼먹었다..ㅎ)

package practice;

public class StarTest6 {

	public static void main(String[] args) {
		int row = 5;
		int col = 5;
		for(int i = 0; i < row; i++) {
			for(int j = col-1; j >= 0; j--) {
				if(j <= i) {
					System.out.print("*");
				}else {
					System.out.print(" ");
				}
			}
			System.out.println();
		}
	}

}

>> 결과

    *
   **
  ***
 ****
*****

 

[5] 마름모 출력하기

package practice;

public class StarTest5 {

	public static void main(String[] args) {
		int n = 5;
		int mid = n/2;
		
		for(int i = 0; i < n; i++) {
			for(int j = 0; j < n; j++) {
				if(i <= mid) { //상단
					//가운데를 기준으로,
					//2-i <= j <= 2+i 일때에 출력
					if((j >= mid-i) && (j <= mid+i)) {
						System.out.print("*");
					}else {
						System.out.print(" ");
					}
				}else { //하단
					int k = (n-1)-i; //임시변수k 새로 만들어줘야함
					if((j >= mid-k) && (j <= mid+k)) {
						System.out.print("*");
					}else {
						System.out.print(" ");
					}
				}
			}
			System.out.println();
		}
	}

}

>> 결과

  *  
 *** 
*****
 *** 
  *

 

 

▼ 제어문은 예제 위주로 정리하려 한다..

 

----------------------------------------------------------------------------------------------------------------------

 

[제어문의 종류]

- 제어문이란? Control Statement, 프로그램의 흐름(fow)을 바꾸어주는 명령문

제어문 코드 내용
조건문

if, if-else 제한을 두거나 범위를 지정하여 선택
switch-case 다차원 선택 (조건식에 따라 여러개의 결과값으로 이동, 명령 수행)
반복문
(Loop)
for 반복 횟수를 알 때 주로 사용
while 반복 횟수를 모를 때 (화일 처리/키보드입력)
do while 반복 횟수를 모르고, 특정 명령 수행 후 지속여부 확인 후 반복 시 사용
기타 break switch-case 또는 반복문에서 종료 역할. //제어문 밖으로 
continue 반복문에서만 사용 가능 //반복문의 끝으로 이동
return  

* 객체지향에서 다루는 제어자(motifier)와는 다르다.

* printf의 제어문자 \n, \r... 는 다른 말로 이스케이프라고 하고, 위 제어문과 다르다.

  (프로그래밍 문법을 번역할 때 '제어'를 붙이는 경우가 참 많은 것 같은데... ;; 그럴 땐 원어를 보면 될 것 같다.)

 

1. 조건문 - if, switch

 조건문은 말 그대로 알고리즘 내에 [조건]을 걸어 선택을 할 때 사용
 - if문, if-else
 - switch : 다차원 선택

 

1) If문

 

(1) if문 예제_명령프롬프트에서 받은 숫자 확인

package practice;

public class PromptTest {

	public static void main(String[] args) {
		String input = args[0];
		int num = Integer.parseInt(input);
		
		if(num == 0) {
			System.out.println("입력한 숫자는 0입니다.");
		}
		
		if(num != 0) {
			System.out.println("입력한 숫자는 0이 아닙니다.");
		}
		
	}

}

>> 결과 (argument : 3)

입력한 숫자는 0이 아닙니다.

 

(2) if - else문

- 자바는 자바스크립트와 달리 else if문이 없다.

- if - else문 안에 중첩된 if-else문이 마치 else if문처럼 보이는 것.. 

package mymain;

import java.util.Scanner;

public class _02_Ex_if4 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int kor; //나의 국어점수
		String grade = "F"; //결과(나의 등급)
		System.out.print("국어 : ");
		kor = scanner.nextInt();
		
		//등급 세분
		
		if(kor>=0 && kor<=100) 
		{
			if(kor>=96) grade = "A+";
			else if(kor>=93) grade = "A";
			else if(kor>=90) grade = "A0";
			else if(kor>=86) grade = "B+";
			else if(kor>=83) grade = "B";
			else if(kor>=80) grade = "B0";
			else if(kor>=76) grade = "C+";
			else if(kor>=73) grade = "C";
			else if(kor>=70) grade = "C0";
			else if(kor>=66) grade = "D+";
			else if(kor>=63) grade = "D";
			else if(kor>=60) grade = "D0";
			else if(kor>=56) grade = "F+";
			else if(kor>=53) grade = "F";
			else if(kor>=50) grade = "F0";
		}
		else
		{
			System.out.printf("입력된 점수 [%d]는 유효하지 않습니다.",kor);
		}
		
		System.out.printf("국어점수 : %d(점) --> 등급 : %s\n",kor,grade);
		
		scanner.close();
	}

}

 

▼ 위 코드는 사실상

    1) if(kor >= 96) else 가 있을 때

                       2) else안에 : if(kor>=93), if(kor>=90)......이 들어있는 것과 같음.

 

(3) 중첩 if문에서 코드를 간결히 하기 _ 위의 원리를 알면 아래와 같이 &&로 일일히 범위 지정을 하지 않을 수 있다.

package mymain;

import java.util.Scanner;

public class _02_Ex_if3 {

	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int kor; //나의 국어점수
		//String grade="ABCDF"; //등급
		char result = 'F'; //결과(나의 등급)
		System.out.print("국어 : ");
		kor = scanner.nextInt();
		
		//효율적 코드 
		//방법 1)
		/*
		if(kor>=90 && kor <= 100) 
			result = grade.charAt(0);
		else if(kor>=80 && kor <90) 
			result = grade.charAt(1);
		else if(kor>=70 && kor <80) 
			result = grade.charAt(2);
		else if(kor>=60 && kor <70) 
			result = grade.charAt(3);	
		*/
		//방법 2)
		//유효범위를 먼저 체크(0~100)
		if(kor>=0 && kor<=100) 
		{
			if(kor>=90) result = 'A';
			else if(kor>=80) result = 'B';
			else if(kor>=70) result = 'C';
			else if(kor>=60) result = 'D';
			//else grade = 'F';
		}
		else
		{
			System.out.printf("입력된 점수 [%d]는 유효하지 않습니다.",kor);
		}
		
		System.out.printf("국어점수 : %d(점) --> 등급 : %c\n",kor,result);
		
		scanner.close();
	}

}

 

2) switch문

 - 다차원 선택
 - break를 걸지 않으면 내 case의 명령 이후에, 다음 case의 명령, 그 다음 case의 명령.... 수행

- 로그인한 사용자의 등급을 체크하여 권한을 부여하는 코드

//break를 안 쓰면 grantDelete()부터 아래까지 명령 하나씩 실행
//level 2면, grantWrite(), grantRead() 실행

switch(level){
	case 3 : grantDelete();
    case 2 : grantWrite();
    case 1 : grantRead();
}

- 계절 예제

package mymain;

import java.util.Scanner;

public class _04_Ex_switch2_계절구하기 {
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		
		int month;
		String season = "";
		
		System.out.print("월 : ");
		month = scanner.nextInt();
		
		//유효성 검사
		if(month >= 1 && month <= 12) {
			//계절 구하기__방법1
			switch(month) 
			{
				case 3: case 4:  case 5: season="봄";     break;
				case 6: case 7:  case 8: season="여름";   break;
				case 9: case 10: case 11: season= "가을"; break;
				default : season="겨울";
			}
		}else {
			System.out.println("월은 1~12사이 값을 입력하세요.");
		}
		
		System.out.printf("[%d월]의 계절은 [%s]입니다.",month,season);
		
		scanner.close();
	}

}

 

- 학점 내기 예제_ switch의 조건식에서 연산자 /를 통해 몫을 구함

package mymain;

import java.util.Scanner;

public class _05_Ex_switch3_문제 {

	public static void main(String[] args) {
		//1.국어점수 입력받는다.
		//2. switch문을 이용해서 등급을 산출하세요.(ABCDF)--수식활용(10배)
		
		Scanner scanner = new Scanner(System.in);
		
		System.out.print("국어 점수 : ");
		int score = scanner.nextInt();
		char grade = 'F';
		
		//유효성 확인
		if(score>=0 && score<=100) {
			//등급내기
			switch(score/10) 
			{
				case 10 : 
				case  9 : grade = 'A'; break;
				case  8 : grade = 'B'; break;
				case  7 : grade = 'C'; break;
				case  6 : grade = 'D'; break;
				default : grade = 'F';
			}
			
			System.out.printf("[%d]점일 때, 등급은 [%c]입니다.",score,grade);
			
		}else {
			System.out.println("유효하지 않은 값입니다.(0~100사이)");
		}
		
		scanner.close();
	}

}

 

- 가위바위보 예제

package practice;

import java.util.Scanner;

public class SwitchTest {

	public static void main(String[] args) {
		//가위(1) 바위(2) 보(3)
		
		String[] optArr = {"","가위","바위","보"};
		
		Scanner scanner = new Scanner(System.in);
		System.out.print("가위(1), 바위(2), 보(3) 중 하나 선택 : ");
		int user_num = scanner.nextInt();
		
		int comp_num = (int)(Math.random()*3)+1;
		
		if(user_num==1 || user_num==2 || user_num ==3) {
			switch(user_num - comp_num) {
				case -2 : case 1 : 
					System.out.printf("당신 : [%s] vs 컴퓨터 : [%s] = 당신의 승!\n", optArr[user_num], optArr[comp_num]);
					break;
				case -1 : case 2 :
					System.out.printf("당신 : [%s] vs 컴퓨터 : [%s] = 비겼네요.\n", optArr[user_num], optArr[comp_num]);
					break;
				default :
					System.out.printf("당신 : [%s] vs 컴퓨터 : [%s] = 졌네요.ㅠㅠ\n", optArr[user_num], optArr[comp_num]);
			}
		}else {
			System.out.println("잘못 입력했습니다.");
		}
		
		scanner.close();
	}

}

>> 결과

가위(1), 바위(2), 보(3) 중 하나 선택 : 3
당신 : [보] vs 컴퓨터 : [가위] = 졌네요.ㅠㅠ

 

2. for/while/do-while

 - for    문 : 반복횟수를 알 때
 - while 문 : 반복횟수를 모를 때(화일처리/키보드입력)
      pf. 파일 처리의 경우
      --> 사용자가 file을 선택하여 읽을 것
      --> 개발자는 file에 몇개의 글자수가 있을지 모른다. 
      --> 이럴 경우, while문으로 file의 끝까지 읽어라 명령

 

1) for문

 for문은 반복횟수를 알고 있을 때 사용하기 용이하다.

 

(1) for문

 

- 양의 정수의 합 구하기 : 1+2+3+...+num

package practice;

public class SumTest {

	public static void main(String[] args) {
		int num = 10;
		int sum = 0;
		
		for(int i = 1; i <= num; i++)
		{
			sum += i;
		}
		System.out.println("sum : "+sum);
	}

}

>> 결과

sum : 55

 

- 짝수의 합 구하기 : 2+4+...+num / 1+3+...+num

package practice;

public class EvenOdd {

	public static void main(String[] args) {
		
		int num = 20;
		int sum = 0;
		
		//짝수의 합 구하기
		
		//방법1 _ if문 활용 
		//두번째 차례만 출력 : 1 (2) 3 (4) 5 (6)
		
		for(int i = 0; i <= num; i++)
		{
			if(i % 2 == 0)
			{
				sum += i;
			}
		}
		System.out.println("sum : "+sum);
		
		sum = 0;
		
		//방법2 _ for문 내 증감식 활용
		//증감을 +2씩 : 2 4 6 8 10 
		
		for(int i = 0; i <= num; i+=2)
		{
			sum += i;
		}
		System.out.println("sum : "+sum);
	}

}

>> 결과

sum : 110
sum : 110

 

- 'A'부터 'Z'까지 문자 출력하기 

(1) ASCII 코드 A : 65, Z : 90, a : 97임을 활용 
    pf. int ch = 'A'; 가 가능한 이유는? char은 JAVA에서 2byte이며, int는 4byte. 더 큰 타입으로는 자동 형변환
(2) System.out.printf의 형식지정자(formatter) %c 활용
    - System.out.printf("%c",65);  의 결과는 'A' 
    - System.out.printf("%d",'A'); 는 안 됨
      **why? 그렇게 메서드가 정의되어 있음. (외울 때 Tip. 출력은 디코딩이니 'A' -> %d는 안되는 걸로)
package practice;

public class CharTest {

	public static void main(String[] args) {
		//A부터 Z까지 출력
		//Ascii에서 A : 65, Z : 90, a : 97
		
		//방법1_아스키 10진수 직접 입력
		for(int i = 65; i <= 90; i++) {
			System.out.printf("%c",i);
		}
		System.out.println();
		
		//방법2_Char to Int 자동 형변환
		for(int i = 'A'; i <= 'Z'; i++) {
			System.out.printf("%c",i);
		}
		System.out.println();
	}

}

>> 결과

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ABCDEFGHIJKLMNOPQRSTUVWXYZ

 

- 'A'부터 'Z'까지 중 3번째 차례 뒤에 구분문자(delim) 넣기

package practice;

public class CharTest2 {

	public static void main(String[] args) {
		//A~Z사이에 구분문자(delim) 넣기
		//ABC-DEF-....
		
		char delim = '-';
		
		//방법1_012-345... 
		//n번 반복/ n번 중 3의 나머지가 2일 때 delim (출력시 'A'+n)
		
		for(int j = 0; j < 26; j++) {
			if(j % 3 == 2) {
				System.out.printf("%c%c",'A'+j,delim);
			}else {
				System.out.printf("%c",'A'+j);
			}
		}
		System.out.println();
			
		//방법2_65 66 67 - 68 69 70 - ... 
		//n번 반복/'A'부터 'Z'중 3의 나머지가 1일 때 delim
		for(int i = 'A'; i <= 'Z'; i++) {
			if(i % 3 == 1) {
				System.out.printf("%c%c",i,delim);
			}else {
				System.out.printf("%c",i);
			}
		}
		System.out.println();
	}

}

>> 결과

ABC-DEF-GHI-JKL-MNO-PQR-STU-VWX-YZ
ABC-DEF-GHI-JKL-MNO-PQR-STU-VWX-YZ

 

 

(2) 중첩 for문

 

- 5x5 블럭쌓기 

package practice;

public class BlockTest {

	public static void main(String[] args) {
		
		int col = 5;
		int row = 5;
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j < col; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

}

>> 결과

*****
*****
*****
*****
*****

 

- 반 피라미드 블럭 쌓기

package practice;

public class BlockTest2 {

	public static void main(String[] args) {
		
		int row = 5;
		
		for(int i = 0; i < row; i++) {
			for(int j = 0; j <= i; j++) {
				System.out.print("*");
			}
			System.out.println();
		}
	}

}

>> 결과

*
**
***
****
*****

 

2) While문

- 반복횟수 모를 때에(파일 처리/키보드입력)

 

- 파일 읽기

(가정) 프로젝트 폴더에 "test.txt"에 아래와 같이 적었다고 가정

Hello,
my love
package practice;

import java.io.FileReader;
import java.io.IOException;

public class FileTest {

	public static void main(String[] args) throws IOException, InterruptedException {
		//파일을 읽어볼 때
		//io안의 클래스 FileReader
		    //메서드 read() - 파일읽기, close() - 파일닫기 
		FileReader file = new FileReader("test.txt");
		int ch = 0;
		int cnt = 0;
		
		//파일을 문자가 없을 때까지 한 문자씩 반복해서 읽고 출력
		//**몇개의 문자가 있을지 모른다.
		while(true) 
		{
			ch = file.read();
			
			if(ch == -1) break; //문자없을 때 반복문 나가기
			
			System.out.printf("%c",ch);
			Thread.sleep(100);
			
			cnt++;
		}
		System.out.println("\n-----------------------");
		System.out.println("총 문자 수 : "+cnt);
		
		file.close();
	}

}

>> 결과

Hello,
my love
-----------------------
총 문자 수 : 15

**** 총 문자 수가 15가 나온 이유 :

      ','과 공백 포함 보이는 문자는 13개 + Enter(실제 코드 : \r\n)   

                                                       <<--- \r,\n처럼 눈에 안 보이는 문자를 화이트 문자라고 한다.

 

- 키보드 입력

(아래 프로그램 흐름) 

※ 참조 : 키보드 버퍼, https://dogrushdev.tistory.com/39

자바 프로그램   RAM   외부 입력 장치
int ch System.in.read() 키보드 버퍼 키보드
  (문자 1byte씩 읽고
int형으로 return)
(임시 저장) (사용자가 입력 후 
엔터를 치면 버퍼로 이동)
package practice;

import java.io.IOException;

public class KeyBoardTest {

	public static void main(String[] args) throws IOException, InterruptedException {
		
		int ch;
		int cnt = 0;
		
		//사용자에게 입력 안내
		System.out.println("문자를 입력하세요.(종료 시 : Ctrl + Z)");
		
		//사용자가 Ctrl+Z를 누를 때까지 반복해서 버퍼 내용을 읽기
		while(true)
		{
			ch = System.in.read();
			
			if(ch == -1) break;
			
			System.out.printf("%c",ch);
			
			Thread.sleep(100);
			
			cnt++;
		}
		System.out.println("\n------------------");
		System.out.println("총 문자 수 : "+cnt);
	}

}

 

- 키보드 입력2 

package mymain;

import java.io.IOException;

public class _12_Ex_while3_키보드입력2 {

	public static void main(String[] args) throws IOException {
		//키보드 표준장치명 : System.in (byte씩 입력)
		  //사용자가 언제 끝낼 지 결정 - 개발자는 반복횟수 알 수 없음
		
		int ch;
		int total_count = 0; //총 입력 문자수
		int number_count = 0; //숫자문자 갯수
		int alpha_upper_count = 0; //대문자 갯수
		int alpha_lower_count = 0; //소문자 갯수
		int white_count = 0; //white문자 갯수 : (\r,\n,\t,'')
		int etc_count = 0; //나머지 문자 갯수
		
		System.out.println("값을 입력하세요(종료 : Ctrl + Z)"); 
		//운영체제의 CL(명령 라인)에서 Ctrl+z는 종료의 단축키
		
		while(true)
		{
			ch = System.in.read(); 
			
			if(ch == -1) break; //System.in.read()가 -1반환
			
			//총 입력 갯수 카운트(EOF 제외)
			total_count++;

			//수문자 갯수 카운트
			if(ch >= '0' && ch <= '9') 
				number_count++;
			
			//대문자 갯수 카운트
			else if(ch >= 'A' && ch <= 'Z') 
				alpha_upper_count++;
			
			//소문자 갯수 카운트
			else if(ch >= 'a' && ch <= 'z') 
				alpha_lower_count++;
			
			//白문자 갯수 카운트
			else if(ch == '\r' || ch == '\n' || ch == '\t'  || ch == ' ') 
				white_count++;
			
			//나머지 갯수 카운트
			else
				etc_count++;
			
			System.out.printf("%c",ch);
		}
		System.out.printf("전  체 갯수 : %2d\n",total_count);
		System.out.printf("숫  자 갯수 : %2d\n",number_count);
		System.out.printf("대문자 갯수 : %2d\n",alpha_upper_count);
		System.out.printf("소문자 갯수 : %2d\n",alpha_lower_count);
		System.out.printf("화이트 갯수 : %2d\n",white_count);
		System.out.printf("나머지 갯수 : %2d\n",etc_count);
		System.out.println("-----[END]-----");
		
		
	}

}

 

 

3) do-While문

- 반복횟수 모를 때에 용이
- 특정 명령을 행한 뒤(do), (사용자의 의사에 따라) 지속할 지 확인(confirm) 후 반복할 때 사용.
package practice;

import java.util.Scanner;

public class Dan99Test {

	public static void main(String[] args) {
				
		int dan = 0;
		String yn = "Y";
		Scanner scanner = new Scanner(System.in);
		
		do
		{
			System.out.print("단 입력(2~9단 중 하나) : ");
			dan = scanner.nextInt();
			
			if(dan >= 2 && dan <= 9) {
				for(int i = 1; i <=9; i++) {
					System.out.printf("%d x %d = %2d\n",dan,i,dan*i);
				}
				System.out.print("더 하시겠습니까? (y/n) :");
				yn = scanner.next();
			}else {
				System.out.println("2~9 중 하나를 입력해주세요.");
			}
		}while(yn.equals("Y") || yn.equals("y"));
			
		scanner.close();
	}

}

>> 결과

단 입력(2~9단 중 하나) : 10
2~9 중 하나를 입력해주세요.
단 입력(2~9단 중 하나) : 3
3 x 1 =  3
3 x 2 =  6
3 x 3 =  9
3 x 4 = 12
3 x 5 = 15
3 x 6 = 18
3 x 7 = 21
3 x 8 = 24
3 x 9 = 27
더 하시겠습니까? (y/n) :n

국비지원수업에서 배운 연산자에 대해서 이론적인 부분을 복습해보았다..

 

-------------------------------------------------------------------------------------------------------------------------------

 

[연산자의 종류]

- 연산을 할 때는 1) 우선순위, 2)자료형을 고려해야 한다. 

우선순위 단항연산자   연산순서
높음 최우선 연산자 (괄호)  
단항연산자 ~, !, ++, --, (cast), -(부호) <--
산술연산자 + , - , * , /(몫) , %(나머지) -->
쉬프트 연산자
(=2진 연산자)
>>, <<, >>> -->
관계 연산자 >, >=, <, <=, ==, != -->
이진논리연산자 &, ^, |,  >> -->
일반논리연산자 &&(AND), ||(OR) -->
삼항연산자 (조건) ? 값(참) : 값(거짓) <--
대입연산자 =  
낮음 (복합 대입 연산자) +=, -=, *=, /=, %=, &=, ^=, |=, >>=, <<= <--

 

1. 단항 연산자 : ~, !, ++, --, (cast), -(부호)

> 단항의 앞에 사용하는 연산자이다.

 

(1) ~ (tilde) : 이진 논리 Not 연산자 (1의 보수)

//Tilde ~ : 2진수로 표현했을 때의 1의 보수

class Tilde{
	public static void main(String[] args){
    	int n = 10; 
		System.out.printf("[%32s]\n",Integer.toBinaryString(n));
		System.out.printf("[%32s]\n",Integer.toBinaryString(~n));
    }
}

>> 결과

[                            1010]
[11111111111111111111111111110101]

 

(2) ! : 일반논리 Not연산자

class NotOperator{
	public static void main(String[] args){
    	boolean bOk = !(3>2); //boolean bOk = !3>2; 는 불가 why? 일반논리일 경우에만 !사용 가능
		                      //(3>2) == true
		System.out.printf("!(3>2) : %b\n",bOk);
		System.out.printf("!true : %b\n",!true);
    }
}

 

>> 결과

!(3>2) : false
!true : false

 

(3) ++(증가), --(감소) : 증감 연산자

- 전위형 : ++n --> 산술연산, 명령이 있기 전에 먼저 변수값을 +1한다. (먼저 변수값을 +1)

- 후위형 : n++ --> 산술연산, 명령이 있은 후에 변수값을 +1한다. (마지막에 변수값을 +1)

public class PlusplusOperator {

	public static void main(String[] args) {
		int x = 1;
        int y = 2;
        int z;
        
        z = ++x + y++;
        System.out.printf("x : %d, y : %d, z : %d\n",x,y,z);
	}

}

>> 결과

x : 2, y : 3, z : 4

//z = ++x + y++; 의 연산 순서   
//1) ++x                 --- > x = x + 1;  //2
//2) x + y               --- > 2 + 2
//3) z = x + y           --- > z = 4;
//4) y++                 --- > y = y + 1;  //3

 

(4) -(부호) : (-1)을 곱해주는 연산자

 

(5) 강제 형변환 연산자 : cast 연산자

Casting

1. 자동 형변환 
   1) 연산시 : 자료형이 큰 쪽으로 자동 형변환
   2) 대입시 : '='를 기준으로 좌변항이 더 큰 자료형일 경우 좌변형의 자료형으로 자동 형변환

2. 강제 형변환 : '(자료형) 변수' 형식

**자동 형변환시, 프로모션(큰쪽으로 형변환)된다.
**강제 형변환시, 디모션(작은쪽으로 형변환)이 가능하나, 오버플로우의 가능성을 염두해야한다.

 

2. 산술연산자 : 사칙연산

- 사칙연산 시, 위의 Casting 방식에 따라 자동 형변환이 이루어짐.

** int보다 작은 정수형 자료형의 경우, 사칙연산 시 결과가 int형으로 나타남

  ex. byte + byte = int 

  why? 중앙처리장치 안의 연산기(ALU)를 통해 연산이 이루어지는데, 계산 시 4byte단위로 결과를 냄 

  ---> 결과적으로 int 타입으로 변환

 

3. 쉬프트연산자(=2진 연산자) : 2진수로 표현한 값에서 >>우측으로 가고, <<좌측으로 가기

- >> : 우측으로 가고, 앞쪽을 부호로 채우기

- << : 좌측으로 가고, 뒤쪽을 0으로 채우기

- >>> : 우측으로 가고, 앞쪽을 0으로 채우기

 

4. 관계연산자 : >, >=, <, <=, ==, !=

 

5. 이진논리연산자 

package mymain;

public class _05_이진논리연산자 {

	public static void main(String[] args) {
		//5. 이진논리연산자
		System.out.printf("[%32s]\n",Integer.toBinaryString(7));
		System.out.printf("[%32s]\n",Integer.toBinaryString(5));
		
		System.out.printf("[%32s]\n",Integer.toBinaryString(7&5));
		System.out.printf("[%32s]\n",Integer.toBinaryString(7|5));
		System.out.printf("[%32s]\n",Integer.toBinaryString(7^5));
		
		// & ^ | >>의 활용 사례
		
		int birthday = 0x19880815; //실제로 birthday일케 안씀... 4bit가 8개.. 32bit --> int 형
		
		System.out.printf("생년월일 : %x\n",birthday); // 19880805 '0805'제외 하고자함
		
		  //출생년도 추출
		int year = birthday >>> 16; // 16bit만큼 밀기 (16진수 하나당 4bit * 4), 앞 공간(부호영역) 양음수 상관없이 0으로 채워짐
		System.out.printf("출생년도 : %x년\n",year);
		
		  //출생월 추출
		             //0x00198808               
		int month = birthday >>> 8 & 0x000000ff;   //소거(0일때 거짓, 1일때 참. 0&0=0. 1&1=1 >> 1이 있는 쪽은 살아남)
		System.out.printf("출생월 : %02x월\n",month);
		
		  //출생일 추출
		int day = birthday & 0xff;
		//int day = birthday & 0x000000ff; 
		System.out.printf("출생월 : %02x일\n",day);
		
		  //출생연월도에서 월을 수정 - 기존 : 0x19980815
		  //1. 월의 자리를 소거 (^)  -- ^은 서로 배타적일 때 참(1), 그렇지 않으면 거짓(0) >> 1010과 1010은 같음 --> 0000이 됨
		birthday = birthday ^ 0x0000800;
		System.out.printf("생년월일 : %x\n",birthday);
		
		  //2. 추가하고 싶은 월 값 추가 (현재 : 0x19880015)   0 : 0000   5 : 0101
		  //                    |       0x00001100    1 : 0001   0 : 0000
		  //                                              0001       0101
		birthday = birthday | 0x00001100; // |는 추가(0 또는 1 = 1 >> 1010 또는 1001은 1011) 
		System.out.printf("생년월일 : %x\n",birthday);
	}

}

>> 결과

[                             111]
[                             101]
[                             101]
[                             111]
[                              10]
생년월일 : 19880815
출생년도 : 1988년
출생월 : 08월
출생월 : 15일
생년월일 : 19880015
생년월일 : 19881115

 

6. 일반논리연산자 : &&(AND), ||(OR)

- 일반논리연산자는 경제적 연산을 한다.

▼ 아래를 보면 경제적 연산을 하기 때문에 dead code 발생

class AndOr{
	public staitc void main(String[] args){
        System.out.println("----[&&]----");
        System.out.printf("true && true : %b\n", (true && true));
        System.out.printf("true && true : %b\n", (true && false));
        System.out.printf("true && true : %b\n", (false && true)); //Alert : Dead Code 
        System.out.printf("true && true : %b\n", (false && false));//Alert : Dead Code 

        System.out.println("----[||]----");
        System.out.printf("true || true : %b\n", (true || true));  //Alert : Dead Code  
        System.out.printf("true || true : %b\n", (true || false)); //Alert : Dead Code 
        System.out.printf("true || true : %b\n", (false || true));  
        System.out.printf("true || true : %b\n", (false || false));
    }
}

- 일반논리연산자 예제 ) 윤년/평년 구하기

package mymain;

import java.util.Scanner;

public class _08_일반논리연산자응용2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		
		int year;
		System.out.print("연도 : ");
		year = scanner.nextInt();
		
		//윤년/평년
		//윤년 조건
		//조건1. 400의 배수가 되는 해 (ex.400년, 800년...2000년)
		//또는
		//조건2. 4의 배수이면서 100의 배수가 아닌 해 
		
		if((/*조건 1*/year%400==0) || (/*조건2*/year%4==0 && year%100!=0)) {
			System.out.printf("[%d]년도는 [윤년]입니다.\n",year);
		}else {
			System.out.printf("[%d]년도는 [평년]입니다.\n",year);
		}
		
		scanner.close();
	}

}

>> 결과

연도 : 2022
[2022]년도는 [평년]입니다.

 

7. 삼항 연산자 : (조건) ? 값(참) : 값(거짓)

class threeOperator{
	public static void main(String[] args){
    	int x = 10;
        int y = 4;
        String z;
        
        z = (x % y ==0)? "맞다" : "아니다";
        
        System.out.printf("%d는 %d의 배수가 %s", x, y, z);
    }
}

>> 결과

10는 4의 배수가 아니다

 

8. 대입 연산자 : =

 

9. 복합 대입 연산자 : +=, -=, *=, /=, %=, &=, ^=, |=, >>=, <<=

int n;
n = 10;
		
n++; // n = n + 1;
n+=2; // n = n + 2;
n-=3; // n = n - 3;

 

 

----------------------------------------------------------------------------------------------------------------------------------

 

[연산자를 활용한 코드 예시]

 

1. 지폐/동전 갯수 세는 코드 

- 산술연산자 /와 %를 활용했을 때에 계산이 간편해짐을 볼 수 있다.

package mymain;

import java.util.Scanner;

public class MoneyCnt {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		int input;
		int tmp;
		int[] moneyArr = {50000, 10000, 5000, 1000, 500, 100, 50, 10}; 
		int[] cntArr = new int[9];
		
		//사용자에게 금액 받기
		System.out.print("금액 : ");
		input = tmp = scanner.nextInt();
		
		//화폐 갯수 세기 : 5만권부터 /와 % 연산자로 갯수 세기
		for(int i = 0; i < moneyArr.length; i++) {
			cntArr[i] = tmp / moneyArr[i];
			tmp = tmp % moneyArr[i];
		}
		
		System.out.printf("---%d(원)에 대한 권종별 갯수---\n",input);
		System.out.printf("50000원 : %d(매)\n",cntArr[0]);
		System.out.printf("10000원 : %d(매)\n",cntArr[1]);
		System.out.printf(" 5000원 : %d(매)\n",cntArr[2]);
		System.out.printf(" 1000원 : %d(매)\n",cntArr[3]);
		System.out.printf("  500원 : %d(개)\n",cntArr[4]);
		System.out.printf("  100원 : %d(개)\n",cntArr[5]);
		System.out.printf("   50원 : %d(개)\n",cntArr[6]);
		System.out.printf("   10원 : %d(개)\n",cntArr[7]);
		System.out.printf("    1원 : %d(개)\n",cntArr[8]);
		
		scanner.close();
	}

}

 

>> 결과

금액 : 258439
---258439(원)에 대한 권종별 갯수---
50000원 : 5(매)
10000원 : 0(매)
 5000원 : 1(매)
 1000원 : 3(매)
  500원 : 0(개)
  100원 : 4(개)
   50원 : 0(개)
   10원 : 3(개)
    1원 : 0(개)

 

2. 섭씨를 화씨로, 화씨를 섭씨로 변환하기 

- 연산자를 사용할 때에 1) 연산 우선순위와 2) 자료형을 고려해야하는 이유를 볼 수 있다.

**잘못된 연산 순서와, 잘못된 자료형의 사용은 잘못된 결과를 나오게 함.

public class FarenCel {

	public static void main(String[] args) {
		// 온도변환
		// 섭씨 -> 화씨 : F = 9/5 * C + 32;
		// 화씨 -> 섭씨 : C = 5/9 *(F-32);
		
		double cel = 7.0;
		double far = 44.6;
		FarenCel.toFar(cel);
		FarenCel.toCel(far);	
	}
	static void toFar(double cel) {
		double result = (cel * 5/9) + 32;
		            //= (double *(int/int)) + int;
		            //= (double * double) + int;
		            //= double + int;
		System.out.printf("섭씨 [%.1f] = 화씨 [%.1f]\n", cel, result);
	}
	static void toCel(double far) {
		double result = (far - 32) * 5/9;
		System.out.printf("화씨 [%.1f] = 섭씨 [%.1f]\n", far, result);
	}
}

>> 결과

섭씨 [7.0] = 화씨 [35.9]
화씨 [44.6] = 섭씨 [7.0]

 

[ Scanner 클래스의 입력 메서드 ]

/*아래의 경우, 
  키보드 버퍼에서 입력구분자(공백 또는 엔터) 전까지 가져온다.*/
next();
nextInt();
nextDouble();
nextBoolean();

/*nextLine();의 경우,
  키보드 버퍼에서 입력구분자(엔터)까지 가져온다. */
nextLine();

1. nextLine()

▼ nextLine() : 입력구분자(엔터)까지 가져옴(ex.홍길동E) --> E빼고 나머지 출력

nextLine()가 홍길동E를 가져옴

 

2. nextDouble() --> nextLine()

▼ nextDouble() : 입력구분자(공백 또는 E) 전까지 가져옴 

▼ nextDouble() --> nextLine() : 앞전에 남은 E를 nextLine()이 가져옴

//해결방법 : scan.nextLine()을 다음에 적어줌

package mymain;

import java.util.Scanner;

public class PrintTest {

	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		
		//콘솔창 입력 : 이름, 나이, 주소, 키, 몸무게
		System.out.print("이름 : ");
		String name = scan.nextLine();
		
		System.out.print("나이 : ");
		int age = scan.nextInt();
		scan.nextLine();
		
		System.out.print("주소 : ");
		String addr = scan.nextLine();
		
		System.out.print("키 : ");
		double height = scan.nextDouble();
		
		System.out.printf("몸무게 : ");
		double weight = scan.nextDouble();
		
		System.out.printf("기타 : ");
		double extra = scan.nextDouble();
		
		scan.close();
		
		//출력
		System.out.printf(" 이름 : %s\n",name);
		System.out.printf(" 나이 : %d\n",age);
		System.out.printf(" 주소 : %s\n",addr);
		System.out.printf("  키 : %.3f\n",height);
		System.out.printf("몸무게 : %.3f\n",weight);
		System.out.printf("기타 : %.3f\n",extra);
	}

}

>> 콘솔 입력 + 결과

이름 : 홍길동
나이 : 30
주소 : 서울시 모모구
키 : 160
몸무게 : 99
기타 : 45
 이름 : 홍길동
 나이 : 30
 주소 : 서울시 모모구
  키 : 160.000
몸무게 : 99.000
기타 : 45.000

 

3. nextDouble() --> nextDouble()

▼ nextDouble() : 입력구분자(공백 또는 E) 전까지 가져옴 

▼ nextDouble() --> nextDouble() : 앞전의 E는 삭제되며, 새로 입력한 텍스트 입력구분자 전까지 가져옴

 

+ Recent posts