728x90

1.Ex06_02) : days03이랑 연결됨.

 

2. Ex01)

package days04;

import java.util.Calendar;

public class Ex01 {

	public static void main(String[] args) {
		
		//캘린더 Duke's Birthday: 01 31,2023 (암기)
		Calendar c = Calendar.getInstance();
		String s1 = String.format("Duke's Birthday: %1$tm %1$te,%1$tY", c); //Duke's Birthday: 01 31,2023
		System.out.println(s1);
		 
		//byte, short, int, long	%d
		
		//byte, short, int, long  %d	10진수
		//byte, short, int, long	%o	8진수
		//byte, short, int, long	%x %X	16진수
		
		
		//%[argument_index$][flags][width][.precision]conversion
		//%									.		 20							f, e, g, a(도 실수형을 나타낼 수 있음)
		//%									#										d
		
		int m=-123;
		System.out.printf("%(d\n", m); //(123)'c'음수를 떼고 ()를 붙여줌
		
		
		int n=10;
		
		
		//10 → 4자리의 숫자 형식으로 출력		0010
		System.out.printf("%04d\n", n); //"%04d\n"에서 0은 flags에 포함 4는 width에 포함 공백에 0을 채워라로 쓰임!
		
		
		//java.util.MissingFormatArgumentException: Format specifier '%o'
		//System.out.printf("%d, %o, %x\n", n);
		System.out.printf("%d, %o, %x\n", n, n, n); //10, 12, a
		System.out.printf("%1$d, %1$o, %1$x\n", n); //1$ 한번에 여러개
		
		
		
		
		
		
		/*
		System.out.printf("%d\n", n); //10
		System.out.printf("%o\n", n); //12
		System.out.printf("%#o\n", n); //012
		System.out.printf("%x\n", n); //a
		System.out.printf("%#x\n", n); //0xa	#차이점 암기
		*/
		
		int money =3256700; //3,256,760
		//Error: Unresolved compilation problem: 
		//		Invalid escape sequence (valid ones are  \b  \t  \n  \f  \r  \"  \'  \\ )
		//System.out.printf("\%d\n", money);
		System.out.printf("\\%d\n", money); //\을 출력하고 싶으면 \\두번 찍어라
		System.out.printf("\\%,d\n", money); //%,d사이에 ,를 찍으면 숫자세는 자리 수 만큼 자동으로 끊어서 읽게 된다.
		
		
		
		//double avg=98.127398;
		//System.out.printf("[%20f]\n", avg); //20은 전체자리수 [           98.127398] 공백이 9칸 오른쪽 정렬
		//System.out.printf("[%-20f]\n", avg); //[98.127398           ] 왼쪽정렬 -면 왼쪽 정렬, +면 오른쪽 정렬
		//System.out.printf("[%20.2f]\n", avg); //[               98.13] 자동으로 3번째 자리에서 반올림
		//System.out.printf("[%.2f]\n", avg); //[98.13]
		//System.out.printf("%.2f", avg);

	}//main()

}//class()

 

3.ex02)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오전 10:41:52
 * @subject 논리연산자
 * @content 1)일반 논리 연산자
 * 								&& 일반논리 ADN연산자(논리곱)
 * 									 참&&참 → 참
 * 								     참&&거짓 → 거짓
 *  								 거짓(f 0)&&참 → 거짓
 *   								 거짓&&거짓 → 거짓
 *   
 *   								 모두 참일 때만 참인 연산자.
 *   
 *   
 * 								|| 	일반논리 OR연산자(논리합)
 * 										참||참→참
 * 										참||거짓→참
 * 									  거짓||참→참
 * 									  거짓||거짓→거짓
 * 
 * 								!	부정(NOT)연산자
 * 										!참→거짓
 * 										!거짓→참
 * 								연산자 우선순위	!> && > ||
 * 
 * 					2)비트 논리 연산자 Ex02_02.java
 * 						
 *
 */
public class Ex02 {

	public static void main(String[] args) {
		// 연산자
		// 1. 산술연사자 + - * / %
		// 2. 비교연산자 > < >= <= == !=
		// 3.논리연산자
		
		//연산자 우선 순위: 산술>비교>논리
		System.out.println(3>5 && 10>7); //false얘는 어차피 거짓이 하나라도 있으면 거짓이기 때문에 앞에 값이 거짓나오면 거짓하고 넘어가기

		System.out.println(3<5 || 10>7); //true 왜냐하면 얘는 하나라도 참이면 무조건 참이기 때문에 앞에 값이 참이기 때문에 더이상 계산 안해도 참
		
		//The operator ! is undefined for the argument type(s) int
		//!int → !는 int앞에서 사용 불가능 하다.
		//System.out.println( !3 < 5 );
		System.out.println( !(3 < 5) );
	}//main

}//class

 

4.ex02_02)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오전 11:11:54
 * @subject 비트 논리 연산자
 * @content	1)&	비트논리 AND 연산자
 * 			2)| 비트논리 OR 연산자
 * 			3)^	 XOR연산자(eXclusive OR)연산자
 * 						    배타적인==서로다른
 * 							서로 다를 때 참인 연산자.
 * 			4)~	비트 부정(틸드) 연산자
 * 
 * 		연산자 우선 순위 ~ > & > ^ > |
 *
 */
public class Ex02_02 {

	public static void main(String[] args) {
		int i=10; //0000 1010
		System.out.println(~i); //-11
		//0000 1010 →	(~)0000 1010 → 1111 0101
		//1111 0101
		//1111 0100
		//0000 1011 (11)
		
		System.out.println(i&3);//2
		//0000 1010
		//0000 0011
		//0000 0010
		System.out.println(i|3);//11
		//0000 1010
		//0000 0011
		//0000 1011
		System.out.println(i^3);//9
		//0000 1010
		//0000 0011
		//0000 1001

	}//main

}//class

 

5.ex03)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오전 11:23:13
 * @subject 
 * @content
 *
 */
public class Ex03 {

	public static void main(String[] args) {
		/*[연산자의 우선 순위가 높은 것 부터 차례대로 나열]
		 * [1].단항연산자	!(not)연산자, cast연산자, ~(틸드), +(양수), -(음수), ++, --(증감연산자) Ex03_02.java
		 * 2.산술연산자 * / %	
		 * 				+ -
		 * 				>> << >>> 쉬프트 연산자
		 * 3.비교연산자	<, >, <=, >=		instanceof(클래스 수업때 배움)
		 * 				==, !=
		 * 4.논리연산자	&	(암기)
		 * 				^
		 * 				|
		 * 				&&
		 * 				||
		 * 5.삼항연산자 == 조건연산자		항1?항2:항3	Ex03_05.java
		 * [6].대입연산자 = += -= 등등
		 * 
		 * [1][6] 단항연사자와 대입연산자는 처리 방향이 : 왼쪽◀◀◀◀◀◀◀◀◀◀◀◀◀◀오른쪽
		 * 그외의 처리 방향은 : 왼쪽 ▶▶▶▶▶▶▶▶▶▶▶▶▶▶▶▶▶▶오른쪽
		 */
		
		// int i = +10; 여기서 +는 양수를 나타내는 부호
		// int i = -10; 여기서 -는 음수를 나타내는 부호

	}

}

 

6.ex03_2)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오전 11:31:55
 * @subject ++ -- 증감 연산자(단항 연산자)
 * @content	증감 연산자
 * 			1)단독으로 사용될 때
 * 				++x(전위)
 * 				x++(후위)
 * 				전위형이든 후위형이든 값이 같음
 * 			2) 다른 수식이나 메서드의 매게변수로 사용될 때에는     Ex03_03.java
 * 				전위형이랑 후위형의 값이 다르다.
 * 				
 *
 */
public class Ex03_02 {

	public static void main(String[] args) {
		// (시험) 어떤 기억 공간의 값을 1증가/(1감소) 시키는 코딩을 하세요.
		//1)x=x+1
		//2)x+=1
		//3)x++
		//4)++x
		
		int x=10;
		System.out.printf(">x=%d\n", x);
		
		//x 기억공간의 값을 1증가 시키는 코딩을 시키겠다. x=x+1
		//x=x+1; //x=x-1(감소코딩)
		
		// += -= *= /= %= <<= >>= ^= |=복합 대입연산자
		//ex) x/=4; x=x/4;
		//ex) x%=4; x=x%4;
		//ex) x*=4; x=x*4;
		//ex) this.textBox1.name=this.textBox1.name+1;
		//ex) this.textBox1.name+=1;
		//x+=1;		// x-=1
		//x++;		//x--		후위형 증감연산자
		++x;		//--x		전위형 증감연산자
		
		System.out.println(x);
		
		
		
		/*
		int i=10;
		//(시험)i를 양→음수, 음→양수 변경하는 코딩을 하세요. 답)*-1 -1을 곱해주면 됨
		i=i*-1; //i=-i도 같은 의미의 표현이다.
		i=-i;
		System.out.println(i);
		*/

	}//main

}//class

 

7.ex03_03)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오전 11:50:57
 * @subject 2)다른 수식이나 메서드의 매개벼수로 사용될 때
 * @content		++x(전위)
 * 				x++(후위)
 * 				다른 수식이나 메서드의 매게변수로 사용될 때에는     Ex03_03.java
 * 				전위형이랑 후위형의 값이 다르다.
 *
 */
public class Ex03_03 {

	public static void main(String[] args) {
		int x=10;
		
		// ++(증감연산자) > =(대입연산자) 연산자 우선순위: ++ > =
		int y= ++x; //전위형 >x=11, y=11 
		System.out.printf(">x=%d, y=%d \n", x, y);
		//int y= x++;	//후위형 int y=x++, ++가 우선순위가 더 높아서 처리하러 왔는데 뒤에 붙어 있기때문에
		//>x=11, y=10					나중에 하겠다는 의미 그래서 int y=x가 먼저 일어나고 그 후, x++이 일어남
		
		System.out.printf(">x=%d, y=%d \n", x, y);
		
		//while(x++<y){} →	x, y 비교먼저 한 후에 x 1증가
		//while(++x<y){} →	x 1증가 후에 비교

	}//main

}//class

 

8.ex03_04)

package days04;

import java.net.MulticastSocket;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 12:13:31
 * @subject 쉬프트 연산자 << >> >>> 
 * @content (비트연산자)
 *			shift==교대하다
 */
public class Ex03_04 {

	public static void main(String[] args) {
		System.out.println(15>>2); 	//3 :첫 부호 비트 1이면 모두 1로 채우고 0이면 모두 0으로 채우겠다 
		System.out.println(15>>>2); //3 :무조건 0으로 채우겠다
		System.out.println(15<<2);	//60 :무조건 0으로 채운다
		
		//15 0000 1111 >> 2
		//	 --00 0011
		//-------------
		//	 0000 0011 → 3
		
		//15 0000 1111 >> 2
		//	 0011 11__
		//-------------
		//	 0011 1100 → 60
		
		
		

	}//main

}//class

 

9.ex03_05)

package days04;
/**
 * @author user
 * @date 2023. 1. 31. - 오후 12:21:39
 * @subject 삼항연산자 == 조건연산자		항1?항2:항3
 * @content								항1 참이면 → 항2만 계산	
 * 										항1 거짓이면→ 항3만 계산
 *
 */
public class Ex03_05 {

	public static void main(String[] args) {
		//삼항연산자=항의 갯수 3개 	1개
		//조건연산자(기능)
		//선언형식:				항1?항2:항3
		//					x>5?x:x+100
		//					참 항2(x)
		//					거짓 항3(x+100)
		int x=3, y;
		
		y=x>5?x:x+100;
		//y=x+100, x>5값이 거짓이므로
		
		System.out.println(y); //103
		

	} //main

} //class

 

10.ex04)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 12:32:33
 * @subject 
 * @content
 *
 */
public class Ex04 {

	public static void main(String[] args) {
		
		char a = 'a'; //97
		char d = 'd'; //100
		char zero = '0';
		char two = '2';
		
		System.out.printf("'%c' %d \n",zero, (int)zero);
		
		System.out.println(two-zero); //'2'-'0'==50-48 → 2
		
		//'d'-'a'==100-97
		System.out.printf("'%c'-'%c'= %d\n", a, d, d-a);
		
		//소문자 'a'-32 빼면 대문자 'A'
		//대문자 'A'+32 더하면 소문자 'a'
		
		char x ='a'-32;
		System.out.println(x);
		

	}//main

}//class

 

11.ex04_02)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 12:42:00
 * @subject 소문자 → 대문자로 변경해서 출력
 * @content
 *
 */
public class Ex04_02 {

	public static void main(String[] args) {
		// 소문자 lowerCase
		// 대문자 UpperCase
		
		char lowerCase = 'a';
		char upperCase;
		//소문자 - 32 = 대문자
		//Type mismatch: cannot convert from int to char
		upperCase=(char)(lowerCase - 32); //lowerCase는 char이고 32는 int형이기 때문에 char으로 강제형변환
		//대문자 + 32 = 소문자
		System.out.println(upperCase);

	}//main

}//class

 

12.ex05)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 12:47:20
 * @subject 
 * @content
 *
 */
public class Ex05 {

	public static void main(String[] args) {
		double pi =3.141592;
		//소수점 3자리 부터 잘라내기.(==소수점 2자리 까지 출력하고 싶다) → 이거 방법 기억하기
		System.out.printf("%.2f\n", pi); //출력할 때 만 사용가능하다
		
		
		//pi=(int)(pi*100)/100; 	//3.0	왜? pi는 double, double*100=double근데 이걸 int강제 형변환/100으로 나눠도 정수형이므로
		pi=(int)(pi*100)/100d;
		System.out.println(pi);
		
		
		
		/*
		pi=pi*100;
		System.out.println(pi); //314.1592
		pi=(int)pi;
		System.out.println(pi); //314.0
		pi=pi/100;
		System.out.println(pi); //3.14
		*/

	}//main

}//class

 

13.ex06)

package days04;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 2:06:35
 * @subject 두 문자열을 비교(시험)
 * @content
 *
 */
public class Ex06 {

	public static void main(String[] args) throws IOException {
		String name="홍길동";
		
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.print(">또 다른 이름(name2)를 입력?");
		String name2 = br.readLine();
		
		System.out.println(">name =" + name);
		System.out.println(">name2 =" + name2);
		
		//두 문자열을 == 연산자로 비교하니깐...False가 나온다
		//System.out.println(name==name2); //False
		
		//참조타입 자료형 이해 필요 : 배열, 클래스(String), 인터페이스
		
		//(암기) 두 문자열을 비교할 때는 == 연산자x, equals()함수를 사용해서 비교한다.
		System.out.println(name.equals(name2)); 

	}

}

 

14.ex07)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 2:19:28
 * @subject 
 * @content
 *
 */
public class Ex07 {

	public static void main(String[] args) {
		// [논리연산자]
		//	1)일반논리연산자: &&, ||, !
		//	2)비트 논리연산자: &, |, ^, ~
		
		//(시험) 수식으로 표현(연산자)
		//(1) x는 10보다 크고, 20보다 작다
		// 		x>10 	&&		x<20
		
		//(2) x는 2의 배수 또는 3의 배수이다.
		//	x를 2로 나누었을 때 떨어진다. 	나머지 0 	x%2==0
		//	x를 3으로 나누었을 때 떨어진다. 나머지 0 	x%3==0
		// 		x%2==0   ||	 x%3==0
		
		//(3) x는 2의 배수 이지만 6의 배수는 아니다.
		//      x%2==0
		//		!(x%6==0)	또는 x%6!=0
		//      x%2==0	&&	x%6!=0
		
		//(4) 문자 ch는 숫자(0~9)이다.
		//		char ch;
		//		ch == '0' || ch=='1' || ch=='2'|| ~~~~||ch='9'
		//		'0' == 48
		//		'9' == 57
		//		48<= ch&&ch <=57
		//		'0'<= ch&&ch <= '9'
		
		//(5) 문자 ch가 대문자 또는 소문자이다.
		//		char ch;
		//		'A' 65
		//		'a' 97
		//		'Z' 90
		//		'z' 122
		// 소문자 lowerCase
		// 대문자 upperCase 
		// (65<=ch&&ch<=90) || ('a' <=ch&&ch<='z')
		

	}//main

}//class

 

15.ex08)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 2:46:55
 * @subject [String → int 형변환]
 * 			[int → String 형변환]
 * 			1) 10+""
 * 			2) Integer.toString(10)
 * 			3) String.valueOf(10)

 * @content
 *
 */
public class Ex08 {

	public static void main(String[] args) {
		//[String → int 형변환]
		/*
		 * int x = 10;
		 * char y =(char)x; 이거는 같은 숫자형이기 때문에 상관없이 강제형변환가능
		 */
		
		//String s = "90";
		//int i = Integer.parseInt(s);
		//int i = (int)s;  ← 왼쪽 처럼은 하면 안된다. 
		//cast라는 연산자로 강제형변환 할 때는 같은 숫자형일때만 변환이 가능하다.
		//            ㄴ 클래스들 간의 형변환
		//System.out.printf("i=%d\n", i);
		
		
		//[int → String 형변환]
		int n=10;
		//첫번째 방법 : String s = 10 + ""; //"10"
		//integer 래퍼클래스 - MAX_VAULE, parseInt()
		/*두번째 방법
		String s=Integer.toString(n);
		System.out.println(Integer.toHexString(n));	//16진수 문자열 반환
		System.out.println(Integer.toOctalString(n)); //8진수 문자열 반환
		System.out.println(Integer.toBinaryString(n)); //2진수 문자열 반환
		*/
		//세번째 방법
		String s=String.valueOf(n);
		System.out.println(s);

	}//main

}//class

 

16.ex09)

package days04;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 3:17:53
 * @subject (시험) 인덱스 연산자 설명 ★★★★★
 * @content			[]
 * 			  String[] args
 *
 */
public class Ex09 {
	
	//main()함수의 매개변수가 String 배열이다.
	public static void main(String[] args) {
		// 국어 점수를 저장할 변수를 하나 선언하세요...
		int kor;
		
		// 국어 점수를 5만명 저장할 변수를 선언하세요...
		/*
		int kor 00001;
			:
			:
		int kor 50000;
		
		int[] kors = new int[50000];
		kors[0]=90;
		System.out.println(kors[0]);
		
		*/
		
		//참조형 - 배열
		/*동일한 자료형으로 여러 개의 기억공간을 할당하는 방법 : 배열
			1.배열 정의? [동일한 자료형]을 메모리 상에 [연속적]으로 놓으게 한 것.
			2.배열 선언 형식
				자료형 [] 배열명 = new 자료형[배열크기];
				자료형 배열명[] = new 자료형[배열크기];
		*/		int[] kors = new int[3];
				// kors:변수, 참조변수(실제기억공간의 값을 참조하는 값이기 때문에), 배열명
				//3	:배열 크기
				//[][][]
				//0 1 2 요소
				//인덱스값(index) == 첨자값
				//LowerBound(아랫첨자값)=0
				//UpperBound(윗 첨자 값)=2		= 배열크기 -1 = 3-1=2
				
		
				//0번째 요소 == 배열명[첨자값]
				kors[0]=90;
				System.out.println(kors[0]);
				
				//배열의 크기:배열명.lenth
				System.out.println(kors.length);
				//UpperBound(윗첨자값) = 배열크기-1=3-1=2
				System.out.println(kors.length -1);
				
				//배열을 사용할 때 주의할 점
				//ArrayIndexOutOfBoundsException:Index 3 out of Bounds for length 3
				//배열 인덱스 예외에서 벗어났다.
				//kors[3]=100;
		
				
				//String[] names = new String[3];
				String[] names = new String[3];
				names[0]="홍길동";
				names[1]="김예지";
				names[2]="서예지";
				
				System.out.println(names[0]);
				System.out.println(names[1]);
				System.out.println(names[2]);
				

	}//main

}//class

 

17.ex10)

package days04;

public class Ex10 {
	public static void main(String[] args){
		int [] kors=null;
		
		//★★★The local variable kors may not have been initialized
		//★★★java.lang.NullPointerException
		kors[0]=90;
		
	}//main
}//class

 

18.ex11)

package days04;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Ex11 {

	public static void main(String[] args) throws IOException {
	      // [days03.Ex05.java  복사 + 붙이기]
	      // 이름, 국어,영어,수학을 입력
	      // 총점, 평균
	      // 형식 출력...
	      // 이름="홍길동",국어=89,영어=78,수학=90,총점=257,평균=85.67
	      String name;
	      int kor, eng, mat;    
	      int tot;  
	      double avg;
	       
	       BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	       
	       System.out.print("> 이름, 국어, 영어, 수학 입력 ? "); // "홍길동, 89, 78, 90"    엔터
	       String input = br.readLine();  // toggle(토글) breakpoint(중단점)  디버깅~   F11       
	       // System.out.println( "> input : " +   input );
	       
	       // "홍길동, 89, 78, 90"     콤마 "구분자로  문자열 잘라내기"    String []  split( 구분자 ) 함수
	       
	       String []  datas =  input.split(",");
	       
	       name =  datas[0]; // "홍길동"
	       kor =  Integer.parseInt(  datas[1].trim()  )  ; //  "89"  String -> int 형변환
	       eng =  Integer.parseInt(  datas[2].trim()  )  ; //  "78"  String -> int 형변환
	       mat =  Integer.parseInt(  datas[3].trim()  )  ; //  "90"  String -> int 형변환
	        
	       
	       // "홍길동"  name 변수 저장
	       // "_98"   문자열 공백 제거  "98"  -> 98 형변환   kor 변수 저장
	       // "_78"   문자열 공백 제거  "78"  -> 78 형변환    eng 변수 저장
	       // "_90"   문자열 공백 제거  "90"  -> 90 형변환  mat 변수 저장 
	      
	     
	       tot          =  kor + eng + mat;        
	       avg = (double)tot / 3;  
	       
	       System.out.printf("이름은 %s이고, 국어=%d, 영어=%d, 수학=%d, 총점=%d, 평균=%f 이다."
	             , name , kor , eng, mat, tot , avg );
	    

	   } // main

}//class

 

19.ex11_02)

package days04;

import java.util.Scanner;

/**
 * @author user
 * @date 2023. 1. 31. - 오후 4:53:24
 * @subject Ex11.java를 Scanner 클래스 사용
 * @content
 *
 */
public class Ex11_02 {

	public static void main(String[] args) {
		// Scanner 클래스 사용
		
		String name;
	    int kor, eng, mat;    
	    int tot;  
	    double avg;
	    
	    Scanner scanner = new Scanner(System.in);
	    
	    System.out.print("> 이름 국어 영어 수학 입력 ?"); //홍길동 90 87 77 얘는 기본 구분자가 공백이므로 띄우기
	    name=scanner.next();
	    kor=scanner.nextInt();
	    eng=scanner.nextInt();
	    mat=scanner.nextInt();
	    
	    tot=kor+eng+mat;
	    avg=(double)tot/3;
	    
	    System.out.printf("이름은 %s이고, 국어=%d, 영어=%d, 수학=%d, 총점=%d, 평균=%f 이다."
	             , name , kor , eng, mat, tot , avg );
	}

}
728x90