JAVA 프로그래밍 기초 (2강)

2020. 12. 30. 09:17java/자바기초강좌

728x90
반응형

 

[Ex1_값바꾸기] 

 a에 100, b에 999를 할당 후 출력하고, 
 서로의 값을 바꾸어 아래 처럼!
 원래 --
 a : 100   b : 999
 바꾼후--
 a : 999   b : 100
*/

 

 

public class Ex1_값바꾸기 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a,b,temp;
		a = 100;
		b = 999;		
		System.out.println("원래--");
		System.out.println("a : "+ a+"\t\tb : "+b);
		temp = b;  // temp : 999   b : 999   temp에다가 b의 값을 넣고
		b = a;	      // b : 100  	a의 값을 b에다가
		a = temp;   // a : c(999)		
		
		System.out.println("\n바꾼후--");
		System.out.println("a : "+ a+"\t\tb : "+b);		
	}
}

결과 화면

 

 

 

[Ex2_문자열] 

문자열 붙이기 

package w2;
//2장 ppt10
public class Ex2_문자열 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		String toolName = "JDK";
		System.out.println(toolName);			// println사용
		System.out.printf("%s\n", toolName);// printf사용
		
		System.out.println(toolName+1.8); // +연결연산자사용
		
		// 1.8 이라는 것이 toString() 메소드에 의해 자동 형변환 됨.
		toolName=toolName+1.8;	// 결과 : JDK1.8
		System.out.println(toolName);
		
		System.out.println("(" + 3 + "," + 5 + ")");
		
	}

}





[Ex3_정수literal] 

package w2;

public class Ex3_정수literal {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int n = 15; 
		int m = 015; // 8진수 
		int k = 0x15; // 16진수
		
		System.out.printf("n : %d\n", n);
		System.out.printf("m :%d\t 8진수로는 %o\n",  m,m);
		System.out.printf("k :%d\t 16진수로는 %x\n", k,k);
	}

}



[실수literal]

package w2;
public class Ex4_실수literal {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		double d = 0.1234d;
		double e = 1234E-4;
			
		System.out.printf("d : %f\t%e\n", d,d);
		System.out.printf("e : %f\t%e\n\n", e,e);
		
		float f = 0.1234f; 
		System.out.printf("f : %f\n", f);
		
		double w = 0.1234d;		// .1234d와 .1234, 0.1234 동일
		System.out.printf("w : %f\n", w);
	}
}


[문자literal]

package w2;
//2장 ppt14
public class Ex5_문자literal {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		char a= 'W';
		char b= '글';	
		char c= '\uae00';
		
		System.out.printf("a : %c\n", a);
		System.out.printf("b : %c\n", b);
		System.out.printf("c : %c\n", c);	
	}
}


[Ex6_특수문자의 출력]

package w2;/*
이름은 홍 길 동, 나이는 20살 체중은 85.5를 변수에 할당 후 , 출력은 아래 처럼!
"홍 길 동"님의
나이는 /20/살이고요,
체중이 '85.5'kg인 대한민국의 남성입니다.
*/
public class Ex6_특수문자의출력 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String name = "홍 길 동";
		int age = 20;
		double weight = 85.5;
		
		// 출력하고자하는 문자앞에 \를 붙임!!
		System.out.printf("\"%s\"님의\n", name);
		System.out.printf("나이는 \\%d\\살이고요,\n", age);
		System.out.printf("체중이 \'%.1f\'kg인 대한민국의 남성입니다.",weight);
	}
}



[Ex7_논리타입literal]

package w2;
//2장 ppt15
public class Ex7_논리타입literal {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		boolean a = true;
		boolean b = 10 > 0;	// 10이 크니까 b = true;
		boolean c = 10 <0;
		//boolean c = 1; 타입 불일치 오류. c/c++과는 달리
		//자바에서 1,0을 참, 거짓으로 사용 불가
		
		System.out.println("a : " + a);
		System.out.println("b : " + b);
		System.out.println("c : " + c);
	}
}


[Ex8_Null literal]

package w2;

public class Ex8_Null_literal {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//double aa = null; // 기본 자료형에서는 null을 사용불가
		String name = null; // Reference 형 자료형에서 사용.
		String irum = "";
		System.out.println("name : "+name );
		System.out.println("irum : "+irum );
		
	}

}


[Ex9_입력]
Scanner sc = new Scanner(System.in)
// new 연산자가 Scanner객체를 생성 후 그 위치를 sc에게 넘김다
// sc를 클로즈 한다. sc.Close();

package w2; /* 실행중 키보드로 입력하여 변수에 할당
정수 a? 100
정수 b? 12
------------------
a + b : 112
a - b : 88
*/
import java.util.Scanner;	
public class Ex9_입력 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// new 연산자가 생성자함수로 Scanner객체를 생성 후, 그 주소를 sa에게 넘김.
		Scanner sc = new Scanner(System.in);
		String line = "--------------------";
		int a, b;
		System.out.print("정수 a? ");a = sc.nextInt();
		System.out.print("정수 b? ");b = sc.nextInt();
				
		int sum = a+b;
		int sub = a-b;
		System.out.println(line);		
		System.out.printf("a + b : %d\t\n", sum);
		System.out.printf("a - b : %d\t", sub);
		
		sc.close();		
	}
}

 

# Scanner의 주요 메소드

#메모 
  1. 자바는 goto문이 없음.
  2. 반복문

while(조건식) {
  문1;
  문2;
} 

   조건식을 만족 못하면 {}안의 문장을 실행 후, 조건식으로 분기
      조건식을 만족 하면 while의 {} 이후의 문장을 실행

  3. 관계연산자 : >, >=, <, <=, ==(같다), !=(같지않다)
     * 주어를 왼쪽으로 하는게 편함
        10 > 0;  10이 0보다 크냐.
   4.  if문

if(조건) // 작업이 하나면 괄호 없이 가능
참;

if(조건) // 두개면 괄호는 반드시
{참;참2}

       조건식을 만족하면 참을 실행
       조건식을 만족못하면 if 다음문을 실행

5. 반복문안에서의 break; 입력 시 반복문을 탈출 한다.

package w2; /* 실행중 키보드로 입력하여 변수에 할당
정수 a? 100
정수 b? 12
------------------
a + b : 112
a - b : 88
정수 a? 2
정수 b? 2 (같은 값 입력시 종료
작업을 종료 합니다.
*/
import java.util.Scanner;	
public class Ex9_입력 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// new 연산자가 생성자함수로 Scanner객체를 생성 후, 그 주소를 sa에게 넘김.
		Scanner sc = new Scanner(System.in);
		String line = "--------------------";
		int a, b;
		
		while(true) // 무한 루프
		{
			System.out.print("정수 a? ");a = sc.nextInt();
			System.out.print("정수 b? ");b = sc.nextInt();
					
			if(a==b )break; // 한줄에 코딩 가능 단순if면
			
			int sum = a+b;
			int sub = a-b;
			System.out.println(line);		
			System.out.printf("a + b : %d\t\n", sum);
			System.out.printf("a - b : %d\t\n\n", sub);
		}
		System.out.println("작업을 종료 합니다.");
		sc.close();	// Scanner 객체 닫기.
	}
}

 

[Ex10_입력]

#메모
 자바에서는 string 비교 시 xxx.equals("") 를 사용한다.

package w2; /*
이름? 홍 길 동
국어, 영어 ?? 90 95
-------------------------
이름 : xxx
국어 : xxx   영어 : xxx
총점 : xxx   평균 : xxx.x
...
이름? (아무런 입력 없이 enter key를 누르면 종료)
끝...
nextLine() : 스캐너객체의 메소드 nextLine()은 \n 전까지의 모든 문자열을 할당.
*/
import java.util.Scanner;
public class Ex11_성적 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		Scanner tc = new Scanner(System.in);
		String line = "----------------------";

		while (true){
			// 기본 값 할당
			
			System.out.print("이름 : ");String name = sc.nextLine();
			if (name.equals("")==true)  // name은 Reference 이므로 직접 =="" 불가!
				break;
			
			System.out.print("국어 ?, 영어? "); int kor = tc.nextInt();
			int eng = tc.nextInt();
			
			// 계산 처리
			int sum = kor + eng;
			float avg =sum /2.0f;
			
			// 출력
			System.out.println(line);
			System.out.printf("이름 : %s\n",name);
			System.out.printf("국어 : %3d\t",kor);
			System.out.printf("영어 : %3d\n",eng);
			System.out.printf("총점 : %3d\t평균 : %5.1f\n\n", sum,avg);
		}
		System.out.println("끝...");
		tc.close();
		sc.close();
	}
}

[Ex12_자동형변환]

package w2;
// 2장 ppt19
public class Ex12_자동형변환 {

	public static void main(String[] args) {
		
//		long m = 25; // 25는 int 타입 25가 long 타입으로 자동 변환
//		double d = 3.14 * 10; // 실수 연산 위해 10이 10.0으로 자동 변환
//		System.out.printf("m : %d\n", m);
//		System.out.printf("d : %.1f\n", d);
		
		// 강제적 형변환
		int n = 300;
		//byte b = n;	// int 타입이 byte로 자동 변환 안 됨.
		// byte의 max가 -127 ~ 127 까지 임
		byte b = (byte)n;
		System.out.printf("b : %d\n", b);
		// 2진수 -> 16진수
		// 4bit 씩 나눠 계산 
		// a = 10 b = 11 c = 12 d = 13 e = 14 f = 15 g = 16
		// int = 300 을 byte로 변환 하면
		// 정수 300 n = 0x 00 00 01 2C = 4BYTE 짜리
		// b = 0x2C = 2 X 16^ X 12x16^
		// 32 + 12 + 1 (0^은 1)
		// 44
//		double b = 1.9;
//		int n = (int)b;
//		System.out.println("n : " +n);
	}
}

 

 

[Ex13_복합산술연산자]

package w2;
/* 복합산술연산자 : +=, -=, *=, /=, %=
 1) a+=10; == a = a + 10;
 2) a-=5; == a = a - 5;
 3) a*=2; == a = a * 2;
 4) a/=10; == a = a / 10;
 4) a%=10; == a = a % 10;
 */
public class Ex13_복합산술연산자 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a = 100;
		//a = a + 10;
		//현 a= 옛a + 10;
		//System.out.printf("a = %d\n", a);
		a+=10;
		System.out.printf("a = %d\n", a);
		a-=5;
		System.out.printf("a = %d\n", a);
		a*=2;
		System.out.printf("a = %d\n", a);
		a/=10;
		System.out.printf("a = %d\n", a);		
		a%=5;
		System.out.printf("a = %d\n", a);		
	}
}

 

[Ex14_화폐매수]

package w2; /*
지불금액? 3276878
--------------------
5만원 : xx장
1만원 : xx장
5천원 : xx장
1천원 : xx장
나머지 금액 : 878원
*/
import java.util.Scanner;
public class Ex14_화폐매수 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.printf("지불금액?");int cash = sc.nextInt();
		String line = "-----------------";
		int a, b, c, d, temp;
		// 총 3,276,878원
		a = cash / 50000;		 // 5만원권 계산
		temp =cash%50000;  // 5만원권을 뺀 잔액
		b = temp / 10000;		// 5만원권을 뺀 잔액에서 1만원 권으로 나눔 
		temp %=10000;  		// 1만원 권 뺀 잔액
		c = temp / 5000;      // 잔액에서 5천원 권으로 나눔
		temp %=5000;  	   // 5천원권 뺀 잔액 
		d = temp / 1000;	   // 잔액에서 1천원으로 나눔
		temp %=1000;		  // 1천원권 뺀 잔액
		
		System.out.println(line);
		System.out.printf("5만원 : %2d장\n", a); // 325만원
		System.out.printf("1만원 : %2d장\n", b); // 2만원
		System.out.printf("5천원 : %2d장\n", c); // 5천원
		System.out.printf("1천원 : %2d장\n", d);	// 1천원
		System.out.printf("나머지금액 : %2d원\n", temp); //878원
		sc.close();
	}
}

 

 

[Ex15_증감연산자]

1. 증감연산자
    1) 전위연산
       i) ++a;
       ii) --a;
     2) 후위연산
       i) a++; == a = + 1 == a+=1;
       ii) b--; == b= b-1 == b-=1;
    3) 변수 단독으로 온 경우 : 전위와 후위의 연산의 결과는 같음
    4) 다른식과 같이 온 경우
       i) 전위의 경우 : 자신이 먼저 증감 후 연산에 참여  
         s = s + ++a;
       ii) 후위의 경우 : 먼저 연산에 첨여 후 , 결과를 넘긴 후 , 최종 순서에 자신이 증감.

package w2;
public class Ex15_증감연산자 {
	public static void main(String[] args) {
		int a = 50, b = 70;
		//++a;		//전위 연산
		//--b;
		a++; 		// 후위 연산
		b--;
		System.out.printf("a : %d\tb : %d\n\n", a,b);	//51, 69
		
		// 전위 연산
		int s =100, t = 200;
		s = s + ++a; //  먼저 a가 1 증가(52), s(100)+a(52) ---> s(152)
		System.out.printf("a : %d\ts : %d\n\n", a,s);	
		t = t+ --b;	// 먼저 b가 1감소 b(68), t(200)+b(68) --> t(268)
		System.out.printf("b : %d\tt : %d\n\n", b,t);	
		
		// 후위 연산
		s = s + a++; // 먼저 s(152)+a(52) --> s(204), 최종순서에 a가 1증가 (53)
		System.out.printf("s : %d\ta : %d\n\n", s,a);
		t = t+b--; // 먼저 t(268)+b(68) --> t(336), 최종 순서에 b가 1감소 b(67)
		System.out.printf("t : %d\tb : %d\n\n", t,b);
		System.out.printf("a : %d\n", ++a); // 54
		System.out.printf("b : %d\n", b--); // 67 출력 후, b가 1감소(66)
		System.out.printf("b : %d\n", b); // 66
	}
}

 

[Ex16_비트 연산자]

^ : 서로 값이 달라야 True 1

package w2;
// 비트 연산자 : &(and), |(or), ~(not), ^(배타적 or)

public class Ex16_비트연산자 {
	
	public static void main(String[] args) {
		byte a = 0b01101010; //2진수로 표시
		byte b = 0b01001110;
		
		System.out.println("a & b : "+ (a & b));
		// 01101010
		// 01001110
		// -----------
		// 01001010
		//  
	}
}
728x90
반응형

'java > 자바기초강좌' 카테고리의 다른 글

JAVA 프로그래밍 기초 (1강)  (0) 2020.12.30