[day05]

1. 배열 array (java에서 많이 쓰진 않는다. 나중에 나올 배열을 자주 씀. 단 이걸 모르면 나중에 나오는걸 모른다)
1) 같은 타입의 여러 변수를 합쳐놓은 것
2) 데이터 저장 공간 수정/ 변경이 안된다
3) 변수 = 값 1 개 저장, 배열은 값 여러개 저장
4) 선언
타입[] 배열명; int[] score;
타입 배열명[]; int score[];


int [] score ;

int : 배열에 저장될 데이터의 타입 (숫자)
[]  : 배열 선언 (이건 배열이다!)
score: 배열에 대한 레퍼런스(참조- 저장위치 주소) 변수 

선언만으로는 배열의 공간이 할당되지 않으며,
score 라는 레퍼런스 변수만 생성된다.  (stack / heap 메모리)
레퍼런스 변수는 배열공간에 대한 주소값 (레퍼런스값)을 가지며
그 변수 자체가 배열은 아니다.
배열 공간이 생성되지 않았으므로 선언만 할시, 레퍼런스 변수의 초기값은 null 이다.
-> 레퍼런스 : 주소, 레퍼런스변수 : 주소를 저장하는 변수

5) 생성

레퍼런스 변수 = new 타입[방개수];
score = new int[5];
new : 메모리 할당 키워드
int : 배열 타입 : 실제 저장될 데이터의 타입
[5] : 배열 방의 개수

6) 인덱스 index
배열의 방은 0부터 시작하는 방번호가 매겨지며 이를 인덱스라 한다.
인덱스를 이용하여 배열의 각 방에 접근 가능.

score[0] = 10;

7) length
배열의 길이 (방개수)를 알여주는 명령어.

score.length --> 5

8) 배열은 연속되는 숫자를 방 번호로 갖고 있어서 (index)
반복문과 함께 자주 사용된다.

9) 초기화
int [] score = {100, 90, 80, 70 60}; //(줄임)
int [] score = new int[]{100,90, 80 ,70, 60}; //(원형)

중괄호 {}안의 요소 개수를 계산해서 방 크기를 자동으로 만들어주고,
순서대로 값도 대입시켜줌, 
선언과 초기화를 따로 분리시키면 에러!!
int [] score;
score = {1,2,3,4} (x) 에러남

int [] score = {1,2,3,4};  

 

package day05;

public class Test40 {
 public static void main (String[] args) {
	 
	 // 중첩 for 문
	 for( int i= 0 ; i < 3 ; i++ ) {
		 for (int j = 0; j <3 ; j++){
			 System.out.println(i + " "+ j );
		 }
	 }

	/* 
	int a = 0 ;
	
	while(a<3) {
		int b = 0 ;	
		while(b<3) {
		
			System.out.println(a+ " " + b);
			b++;
		}
		a++;
	}
*/	 
	 
 }
}
package day05;

import java.util.Scanner;

public class Test41 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	//문제1. 구구단 2단 출력
		// 출력 형태 
		// 2 * 1 = 2
		// 2 * 2 = 4
		// 2 * 3 = 6
	
	//문제2. 구구단의 단수를 입력받아, 해당 단을 출력
		
	//문제3. 구구단 전체 출력 (2단 ~ 9단)
		
		
	//2단출력
/*		int a =	1 ;
		for (;a<10 ;a++) {

			System.out.println(2 + "*"+ a + "=" + ( 2 * a));
	}
*/
		
/*		
	//	
		Scanner sc = new Scanner (System.in); 
		System.out.println("단수를 입력하세요>>");
		int num = sc.nextInt();
		
		for(int i=1;i<10;i++) {
			System.out.println(num + "*" + i + "=" + ( i * num));
			
		}
		sc.close();
*/		
		
		
		
	
/*		
		 for( int i= 1 ; i < 10 ; i++ ) {
			 System.out.println("\n"+"******"+i+"단******");
			 
			 
			 for (int j = 1; j <10 ; j++){
				 System.out.println(i + "* "+ j + "=" +(i * j) );
			 } 
			
		 }
*/
		
/*		
		// 별찍기 
		for(int a = 0; a<5 ; a++) {
			for(int b = 0; b<=a; b++) {
				System.out.print("*");
			}
			System.out.println();
		}
			
*/
/*		for(int i = 1; i < 7; i+=3) {
	         System.out.println("***" + i + "단***\t***" + (i+1) + "단***\t***" + (i+2) + "단***");
	         for(int j = 1; j < 10; j++) {
	            System.out.print(i + " * " + j + " = " + (i * j) + "\t" );
	            System.out.print((i+1) + " * " + j + " = " + ((i+1) * j) + "\t" );
	            System.out.println((i+2) + " * " + j + " = " + ((i+2) * j) );
	         }
	         
	      }
*/		
		
	  //10번 	
		
		
	}

}
package day05;

public class Test41111 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
/*	 //1번 문제 	
		for(int a = 1; a<=5; a++) {
			System.out.println(a+"행 : ***");
			
			
		}
*/			
			
   //  2번 문제 
/*     for(int a = 0; a <=5; a++ ) {
    	 for(int b = 0; b<=a ; b++  ) {
    	 System.out.print("*");
    	}
    	 System.out.println();
     }
*/     
   // 3번문제   
/*     for(int a = 0; a <=5; a++ ) {
    	 for(int b = 5; b>a; b--) {
    	 System.out.print("*");
    	}
    	 System.out.println();
     }
*/
/*	// 4번문제	
	 for(int a = 0; a <=4; a++ ) {
	    	 for(int b = 1; b<=5 ; b++  ) {
	    	 System.out.print(b+a);
	    	}
	    	 System.out.println();
	     }
*/	     
	     //5번
/*	 for(int a = 0; a <=4; a++ ) {
	    	 for(int b = 5; b<=9 ; b++  ) {
	    	 System.out.print(b-a);
	    	}
	    	 System.out.println();
	     }
 */  
	// 6번
		int star = 1;
		boolean flag = true; // 별이 증가하면 true, 별이 감소해야되면 false 
		for(int a = 0; a < 9 ; a++) {
			for(int b = 0; b<star; b++ ) {
				System.out.print("*");
			}
			if(flag) { //== true)
			
				star++;
			}else {
				star--;
			}
			if(star == 5) {
				flag = false;
			}
			System.out.println();
		}
		
		
		
		
		
/*		  for(int a = 0; a <=4; a++ ) {
		    	 for(int b = 0; b<=a ; b++  ) {
		    	 System.out.print("*");
		    	}
		    	 System.out.println();
		     }
		  for(int a = 0; a <=3; a++ ) {
		    	 for(int b = 4; b>a; b--) {
		    	 System.out.print("*");
		    	}
		    	 System.out.println();
		     }
*/
		
		
		
		
/*		for() {int a = 0;a<5; a++
			for(int b = 5 ;b) {
				System.out.println();
			}
*/			 												// 첫번째 for  a의 길이는 칸수를 결정함  
															// 2번째 	for  
/*		 for(int a = 0; a <=4; a++ ) {			
	    	 for(int b = 5; b>a ; b--  ) {
	    	 System.out.print(" ");
	    	}
	    	 	for(int c = 0; c<a+1; c++) {
	    	 	System.out.print("*");
	    	 	}
	    	 System.out.println();
	     }
	     
	     */
		// for(int a = 0; a <=5; a++ ) {
	    //	 for(int b = 5; b>a; b--) {
	    //	 System.out.print("*");
	    //		}
	    //	 System.out.println();
	    //	 }
		
		// 7번문제
/*	 for(int a = 0; a <=4; a++ ) {			
	    	 for(int b = 5; b>a+1 ; b--  ) {
	    	 System.out.print(" ");
	    	}
	    	 	for(int c = 0; c<a+1; c++) {
	    	 	System.out.print("*");
	    	 	}
	    	 System.out.println();
	     }
	*/	
		 //8번문제
/*	 for(int a = 0; a <=4; a++ ) {   
	          for(int c = 0; c<a; c++) {
	              System.out.print(" ");
	          }
	           for(int b = 5; b>a ; b--  ) {
	           System.out.print("*");
	          }
	              
	              
	           System.out.println();
	 }
*/	
/*		 // 10번  삼각형 문제 
	  for(int a = 1 ; a <= 5 ; a++) {
		 for (int b = 5; b>a ; b--) {
			 System.out.print(" ");
		 	}
		 	for (int c = 0; c<2*a-1 ; c++) {
		 		System.out.print("*");
		 	}
		 	System.out.println();
	  }
	  */
	  	//10번 
/*		for(int a=1; a<=5;a++){
			for(int b=0;b<5-a;b++){
				System.out.print(" "); 
			}
			for(int c=0;c<2*a-1;c++){
				System.out.print("*"); 
			}
			System.out.println();
		
		}
*/
	 //11번
/*		for(int a=1; a<=5;a++){
			for(int b=0;b<a-1;b++){
				System.out.print(" "); 
			}
			for(int c=10;c>2*a-1;c--){
				System.out.print("*"); 
			}
			System.out.println();
		}
	*/
	}
	

}

 

 

package day05;

public class Test42 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 배열  선언
		//int a ;
		int [] score;
		
		// a= 10;
		score = new int [3]; // 방 3개 짜리 만들기
		// 선언 + 할당
		int [] score1 = new int [3]; 
	
		score[0] = 10;
		score[1] = 20;
		score[2] = 30;
		System.out.println(score[0]);
		System.out.println(score[1]);
		System.out.println(score[2]);
		
		// int a = score; 은 안들어감 
		int a = score[0];
		int tot = 0;
		for(int i = 0; i<3; i++) {
			tot += score[i];
		}
		System.out.println(tot);
		System.out.println(score.length);
	}

}

 

 

package day05;

public class Test43 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		int [] num = new int [10];
		for(int i = 0; i<10; i++) {
			num[i]= 100;
			System.out.println(num[i]);
		}
		System.out.println("--------------------");
		for(int n: num) {
			System.out.println(n);
		}
				
		// 초기화
		String[] subject = {"java","jsp","spring"};
		
		for(int i = 0; i < subject.length; i++) {
			System.out.println(subject[i]);
		}
		
		System.out.println("--------------------");
	/*	String[] subject = new String[3]; // 
String[0] = java 
		double[] d = new double[3];
		
		
			float [] f = new float[3];
			boolean[] b = new boolean[3];
			
	*/		
		
		// 업그레이드 for 문 (forEach 문)
		for(String a:subject) {
			System.out.println(a);
		}
	}
}

 

 

package day05;

public class Test44 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		
		
		//레퍼런스 치환
	/*	int [] arr = {1,2,3,4,5};
		int [] myArr = arr;
		for(int i = 0; i < myArr.length; i++) {
			System.out.println(myArr[i]);
			
		
		
		arr = null;
			System.out.println(myArr	[i]);
		}
		
	*/	
		//예제. 최대값, 최소값 구하기
		
/*		int [] score = {79, 59, 36, 98, 25};
		// 최대값
		int max = score [0]; 
		for (int i = 0; i < score.length; i++) {
			if( max< score[i]) {
				max = score[i];
			}
		}
		System.out.println("최대값" + max);
		
		//최소값
		int min = score [0];
		for(int i = 0 ; i < score.length; i++) {
			if(min>score[i]) {
				min = score[i];
			}
		}
		System.out.println("최소값"+ min);
*/
		
		
		//===> 더 간단하게 
				int [] score = {79, 59, 36, 98, 25};
		// 최대값
		int max = score [0]; 
		int min = score [0];
		for (int i = 0; i < score.length; i++) {
			if( max< score[i]) {
				max = score[i];
			}
			if(min>score[i]) {
				min = score[i];
			}
		}
		
		System.out.println(max);
		System.out.println(min);
	}
}

 

 

package day05;

import java.util.Scanner;

public class Test45 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		  // 문제1-1. int형 방 5개 배열을 만들고 10,20,30,40,50 을 저장하고, 출력. 
		                                   //    0  1  2  3  4
	      // 문제1-2. 위 배열을 이용하여, 인덱스번호 1번과 3번안에 있는 데이터를 
	      //         더한 값을 출력해보세요. 
	      // 문제1-3. 인덱스번호를 사용자로부터 입력받고, 
	      //         해당 인덱스의 데이터를 출력해보세요. 
	      // 문제1-4. 배열안의 모든 요소의 총 합을 출력해보세요. 
	      // 문제1-5. 배열안에 있는 값(데이터)중 하나를 입력하면, 
	      //         그 값이 저장된 인덱스 번호를 출력해보세요. 
	      // 문제1-6. 인덱스 번호 2번과 4번의 값을 교환해보세요. 
	      // 문제1-7. (심화) 내림차순으로 정렬해보세요.
		
		// 1번 문제
/*		int [] score = {10, 30, 20, 40, 50};
		for(int i =0; i <score.length;  i++) {
		System.out.println(score[i]);
		}
				
		
		// 2번 문제 
		System.out.println(score[1]+score[3]);
		
		// 3번 문제
		Scanner sc = new Scanner(System.in);
		System.out.println("인덱스를 입력하세요>>");
		int num = sc.nextInt();
		System.out.println(score[num]);
		sc.close();
*/		
/*		//4번 문제
		int tot = 0;
		for(int i =0; i <score.length;  i++) {
			tot += score[i];
		}
*/		//5번 문제
/*		System.out.println(tot);
		Scanner sc = new Scanner(System.in);
		System.out.println("값을 입력하세요>>");
		int val = sc.nextInt();
			for(int i = 0; i < score.length; i++){
				if(val == score[i]){
					System.out.println(i);
					break;
		if(val==score[i]) {
		
		}
*/		//6번 인덱스 번호 2번 4번 교환 
		
//		int [] score = {10, 30, 30, 20, 50};
				//       0  1   2   3    4 

		
		//빈공간 생성
		
		
/*		
		int[] temp = new int[1]
		// int tmp = score[2]
		
		//인덱스 2번을 빈공간으로 잠깐 이동
		temp[0] = score[2];
		//int tmp = score[2];
		System.out.println(temp[0]); //20
		
		//인덱스 4번을 2번으로 이동
		score[2] = score[4];
		System.out.println(score[2]); //4
		
		//다시 temp의 값을 4번으로 이동
		score[4] = temp[0];
		socre[4] = tmp;
		System.out.println(score[4]); //3
		
		for(int i=0; i < score.length; i++) {
			System.out.print(score[i]);// 246315
		}
*/		
		//버블 정렬
		
	/*	
		int [] score = {10, 20,50, 40, 30};
  
		for(int i =0; i <score.length-1;  i++) {
			for(int j = i+1; j <score.length; j++) {
		
				if(score[i]<score[j]) {
				 int tmp = score[i]; 
						score[i]=score[j];
						score[j]=tmp;
		
				
				}
			}
		}
		*/	
		  //선택정렬
			int [] score = {10, 20,50, 40, 30};
			for(int i = 0; i < score.length-1; i++) {
				int max = i; //큰수의 인덱스 번호
					
				for(int j = i+1; j<score.length; j++) {
					if( score[max]>score[j]) {
					max = j;
				}
			
			
			
			}
				int tmp = score[i];
				score[i] = score[max];
				score[max] = tmp;
		
	        // 결과값 출력
	      
	        for (int a : score) {
	            System.out.print(a + "  ");
	        	}
	        System.out.println();
	        
			}
	}
}

'P-Language > [Java]' 카테고리의 다른 글

[Java] 7 - 객체지향  (0) 2022.06.03
[Java] 6 - 다차원 배열  (0) 2022.06.03
[Java] 4 - 조건문(switch), 반복문  (0) 2022.06.03
[Java] 3 - 연산자, 제어문, 조건문  (0) 2022.06.03
[Java] 2 - 변수와 입,출력문  (0) 2022.06.03

[day04]

1. 조건문 switch
다중 선택문 : 하나의 변수값을 평가하여, 각 값에 대해 개별적인 처리를 하는 문장.

1) 구조
switch(변수){
case 값1 :  // 값1과 변수의 값이 동일한 경우 아래 샐행문들 실행~
실행문들....
break; // 위 실행문들을 실행하고 switch 강제종료!!
case 값2 : 
실행문들....
break;
case 값3 : 
실행문들....
break;


...
default : 
실행문들....
break; // 마지막 break는 생략가능
}

2) 특징과 주의점
1. switch 문으로 평가 할 수 있는 변수는 주로 정수형, String
(int, char, String) 

2. case 다음에는 반드시 값이 하나가 와야한다.
3. case 0 : .... case 2 : ... 와 같이 반드시 값을 정렬할 필요없다.
4. dafault 는 생략가능
5. case 별로 {}로 묶지 않는다. 콜론 : 으로 영역 인식.
6. 다음 case가 실행되지 않도록 할 경우에는 

2. 반복문 while
1) 조건식을 먼저 검사한 후, 실행하는 반복문 (루프)
2) 실행문 영역 {}안에서 반복(루프)를 종료할 수 있게 만들어 줘야한다.
3) 구조
#1. 반복의 횟수를 알때
변수 = 초기값;
while(조건식){
// 반복해서 실행할 명령문 작성
증감식;
}

#2. 무한반복 : 반복횟수가 달라질때
while(true){
반복해서 실행할 명령문.....
if(조건){break;} //종료시점이 반드시 필요함!!!
}

3. 반복문 do-while  (잘 안씀)

선 실행 후 비교 : 실행 먼저한 후 조건 검사하는 형태

1) 구조
do {
// 반복해서 실행할 명령문...
}while(조건식); // ; 꼭붙일것


4. 반복문 for 
지정된 수만큼 반복할때 사용

1) 구조
                     1         2       4 
for(초기식; 조건식; 증감식;){
// 반복해서 실행할 명령문들....  3
}


1번 -> 2번(조건이 참이면) -> 3번 -> 4번 -> (2 -> 3 -> 4) -> 2번 (거짓-> 종료!)
초기식 : for 문 처음 시작할때 한번만 실행.
조건식 : 결과가 true/ false 되도록
증감식 : 1씩 증/감 할때는 증감연산자(++;) 주로 사용  

package day04;
import java.util.Scanner;

public class Test30 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		Scanner sc = new Scanner(System.in);
		System.out.print("정수 입력>>");
		int num = Integer.parseInt(sc.nextLine());
		
		switch(num) {
			case 1 : 
				System.out.println("1을 입력하셨습니다");
				break;
				
			case 2 :
				System.out.println("2을 입력하셨습니다");
				break;
				
			case 3 :
				System.out.println("3을 입력하셨습니다");
				break;
				
			default :
				System.out.println("1.2.3이 아닌 숫자를 입력하셨습니다");
				break;
			
		}
		System.out.println("프로그램 종료!!");
		sc.close();
	}
}
package day04;

public class Test31 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//char ch = 'A';
		String str = "A" ;
		switch(str) {
		
		case "A" : 
			System.out.println("AAA");
			break;
		case "B" : 
			System.out.println("BBB");
			break;
		case "C" : 
			System.out.println("CCC");
			break;
	
	/*	case 'B' : 
			System.out.println("BBB");
			break;
			
		case 'C' : 
			System.out.println("CCC");
			break;
				*/
		}	
	}
}
package day04;
import java.util.Scanner;
public class Test32 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			
			// *switch 문제 *
			// 문제 1. 정수를 입력받아 3~5는 "봄" 6~8은 "여름",
			//	9~ 11은 "가을", 12 ~2는 "겨울" 을 출력하세요.
	/*	
		System.out.println("정수를 입력하세요");
		Scanner sc = new Scanner(System.in); 	
		int season = sc.nextInt();
		
		switch(season/3) {
			case 1 :
				System.out.println("봄");
				break;
			case 2 :
				System.out.println("여름");
				break;
			case 3 :
				System.out.println("가을");
				break;
				
			case 4 :
				System.out.println("가을");
				break;
			*/
	
		
		
		
			// 문제 2. 점수를 입력받고 90~ 100은 "수", 80~ 89는 "우"
			// 70 ~ 79는 " 미" 60 ~ 69 "양", 그 이하는 "가"를 출력하세요.
	/*
	
	
                 70~79 -> "미"
String str = "A" 

		switch(str) {
		
		case "미" : 
			System.out.println("AAA");
			break;
		case "B" : 
			System.out.println("BBB");
			break;
		case "C" : 
			System.out.println("CCC");
			break;
	
	
	
		System.out.println("정수를 입력하세요") ;
		Scanner sc1 = new Scanner(System.in); 	
		int score = sc1.nextInt();
		


		switch (score/10) { 
			case  : 10 , case 9 :
				System.out.println("수");
				break;

			case  : 8
				System.out.println("우");
				break;
		}
				
				*/
		
			// 문제 3. 덧셈 +, 뺄셈 -, 곱셈 *, 나눗셈/ 중 원하는 기호를 선택하여 
			//	a, b의 연산 결과값을 출력해보세요.
		

		System.out.println("정수를 입력하세요") ;
		Scanner sc1 = new Scanner(System.in); 	
		String op  = sc1.nextLine();
		int a = 10; int b= 5;
		switch(op) {
		case "+" :
			System.out.println(a + b);
			break;
			
		case "-" :
			System.out.println(a - b);
			
		case "*" :
			System.out.println(a * b);
			
		case "/" :
			System.out.println(a / b);
			
			dafault :
				System.out.println("사칙연산이 아닙니다");
		}
	}
}

 

package day04;

import java.util.Scanner;

public class Test33 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		/*
		 * 
		#1. 반복의 횟수를 알때
		변수 = 초기값;
		while(조건식){
			// 반복해서 실행할 명령문 작성
			증감식;
		}

		#2. 무한반복 : 반복횟수가 달라질때
		while(true){
			반복해서 실행할 명령문.....
			if(조건){break;} //종료시점이 반드시 필요함!!!
		}
		 */
		
		int a = 0;   // 초기식
		while(a<=4) {
			// 반복할 명령어
			System.out.println("안녕하세요" + a);
			a++; // 증감식
			
		}
		// 0 ~ 5 출력
		int n  = 0;
		while (n <=5) {
			System.out.println(n);
			n++;
		} 
	
	}
}

 

package day04;

import java.util.Scanner;

public class Test34 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		/*
		#1. 반복의 횟수를 알때
		변수 = 초기값;
		while(조건식){
			// 반복해서 실행할 명령문 작성
			증감식;
		}

		#2. 무한반복 : 반복횟수가 달라질때
		while(true){
			반복해서 실행할 명령문.....
			if(조건){break;} //종료시점이 반드시 필요함!!!
		}
		 */
		
		
		//while 무한반복
		//숫자 0을 입력받을때 까지 계속 정수를 입력받아 출력하세요.
		//
		
		Scanner sc = new Scanner(System.in);
		System.out.println("숫자입력");
		
		while(true) {
			int num = Integer.parseInt(sc.nextLine());
			if(num==0) {
				System.out.println("종료");
				break;
			}
		}
	}
}
package day04;

import java.util.Scanner;

public class Test35 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
//문제 1. 0~ 10 까지 출력해보세요
		/*
		int a = 0;
		while(a<11) {
			System.out.println(a);
			a++;
		}
//문제 2. 1~ 15 까지 출력해보세요
		int b = 1;
		while(b<=15) {
			System.out.println(b);
			b++;
		}
//문제 3. 0~ 100 까지 10단위로 출력해보세요
		int c = 1;
		while(c<=10) {
			System.out.println(c*10);
			c++;
		
		
		int c = 0;
		while(c<=100) {
			System.out.println(c);
			c+= 10;
		}


		/*
		#2. 무한반복 : 반복횟수가 달라질때
		while(true){
			반복해서 실행할 명령문.....
			if(조건){break;} //종료시점이 반드시 필요함!!!
		}
		
		
		
		
//문제 4. 1~ 20 까지 홀수만 출력해보세요
		int d = 1;
		while(d<=10) {
			System.out.println(d*2-1);
			d++;
		}
		
		int d = 1;
		while(d<=20) {
			if(d%2==1){
			System.out.println(d);
			}
		d++;
		}
		
		
			
		
		*/
//문제 5. 1~ 10 까지 총합을 출력해보세요
		// 1 2 3 4 5 6 7 8 9 10
	/*
		   int sum = 0;
	        int i = 1;
	        
	        while (i<=10) {
	            sum =sum + i; // (sum += i;)
	          
	            i++;
	            
	        }
	            System.out.println(sum);
	        }
				 */
			
//문제 6. 1~ 50 까지 짝수의 합 출력해보세요
	 /*
		int tot = 0;
      int i = 1 ;
      
      	while (i<=25) {
          tot =(tot + (i*2));
          i++;
          
      	}
      	System.out.println(tot);
      */
				/*
	  
	      int i = 0;
	      int tot = 0;
	      
	      while(i <= 50) {
	         if(i % 2 == 0) {
	            tot += i;
	         	}
	          i++;
	      }
	      System.out.println(tot);
	   
*/
		
		

					
// 주문 프로그램 		
// 1.아메리카노 2500/		
// 2. 카페라떼 3000/		
// 3. 카푸치노 3500/		
// 4. 카라멜마끼아또 4000/		
// 5. 샌드위치 6000/		
// 6. 종료 		
		//  1. 단계 위 메뉴를 출력하고, 번호로 주문을 받는다.
		//  주문 종료를 선택할때까지 계속 주문을 받고 
		//  주문 받은 모든 메뉴의 총 금액을 출력한 후 종료
		//   2단계 : int money = 20000; (내돈). 
        //   주문시, 내 돈에서 주문한 금액 차감, 돈이 부족하면 주문 못하게, 
        //   주문 종료시 주문한 총 금액과 내 돈의 잔액까지 출력. 

		System.out.println
				("1."+ "아메리카노 2500"+"\n" +		
				 "2."+ "카페라떼 3000 "+"\n" +	
				 "3."+ "카푸치노 3500 "+"\n" +	
				 "4."+ "카라멜마끼아또 4000"+"\n" +	
				 "5."+ "샌드위치 6000" +"\n" +	
				 "6."+ " 주문종료");
		Scanner sc = new Scanner(System.in);
		int tot = 0; // 주문 총금액
		int money = 20000;
		while(true) {
			System.out.println("주문 번호를 입력하세요");
			int num = sc.nextInt();
				if(num == 1) {
						System.out.println("아메리카노를 주문하셨습니다" ); tot += 2500;
					}else if(num == 2) {
						System.out.println("카페라떼를 주문하셨습니다" ); tot += 3000;
					}else if(num == 3) {
						System.out.println("카푸치느를 주문하셨습니다" );	tot += 3500;
					}else if(num == 4) {
						System.out.println("카라멜 마끼아또를 주문하셨습니다" );	tot += 4000;
					}else if(num == 5) {
						System.out.println("샌드위치를 주문하셨습니다" );	tot += 6000;
					}else if(num == 6) {
						System.out.println("총 금액은"+ tot + " 입니다");
						break;
					}else //if(num == 0 || num >6) 
						{
						System.out.println("잘못입력하셨습니다");
						}				
				if(money-tot<0) {
				System.out.println("잔액이 부족합니다");
				
				}
			
		System.out.println("남은 잔액은" + (money - tot) + "입니다");
		
		}
	


		/*
		#2. 무한반복 : 반복횟수가 달라질때
		while(true){
			반복해서 실행할 명령문.....
			if(조건){break;} //종료시점이 반드시 필요함!!!
		}
		
		 
		sc.close();
		*/
			
		
	}
}

 

package day04;

public class Test36 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		int num = 0; // 초기식
		do {
			System.out.println("hello");
			num++; //증감식
		}while(num <1); //조건식
		
	}
}

 

package day04;

public class Test37 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
		
		//5번 반복
	//	for (int i= 0; i < 5 ; i++ ) {
	//		System.out.println("hello");
			
			
		
		
		//0~10까지 출력
	//	for (int i = 0; i<=10; i++) {
	//		System.out.println(i);
	//	}
		
		
		// #1. for문 안에서 만들어진 i 변수는 밖에서 사용 불가
		//System.out.println(i); for문 안에서만 i 동작함  -> i는 지역변수
		
		// #2. i를 밖에서도 사용하고 싶으면 밖에 선언하고 사용
	//	int i = 0 ;
		
		
		
		// #3. 초기값 생략 : 밖에서 먼저 만들어놓은 변수라면 for문 안에서 초기식 생략가능 *단 반드시 세미콜론은 작성
		// for (//(int i = 0); i < 10 ; i++ ){}
		
		// #4. 무한반복
		// for ( ;  ; ){}      == while(true)   가독성 면에서 무한반복은 while을 더 많이씀 for은 쓰다만 느낌
		
		
		// break, continue
		for (int a = 0; a < 10 ; a++) {
			if(a ==5) {
				//break; //강제종료 -> 반복문 종료
				continue; // 다음 동작으로 건너뜀 -> 아래 출력안하고, 증감식으로 가버림
			}
			
		 	System.out.println(a);	
		
		}
	}

}
package day04;

import java.util.Scanner;

public class Test38 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
 //1. 10- 30 까지 출력
 //2.		10 - 100까지 10단위 출력
 //3.		1 - 20 짝수만 출력		
//4.		1- 100까지 홀수의 총합 출력
//5.		정수 1개를 입력받고, 1부터 입력받은 수까지의 합 출력
		/*
		for (int i = 10 ; i <= 30 ; i++ ) {
		System.out.println(i);
		}
		
		//2번
		for (int i = 0; i<= 100 ; i +=10) {
			System.out.println(i);
		}
		
		
		//3번
		for (int k = 0; k<= 20 ; k ++) {
			if (k%2==0) {
				System.out.println(k);
			}
		}
		
		//4번
		int tot = 0; 
		for(int i = 0; i<=100 ; i++) {
			
			if(i%2==1) {
				
				tot += i;
				
			}
			
		}
		System.out.println("홀수의 합은 : " + tot);
		
		
		*/
		/*
		//5.		정수 1개를 입력받고, 1부터 입력받은 수까지의 합 출력
		Scanner sc = new Scanner(System.in);
		int i = 0;
		System.out.println("정수를 입력하세요>");
		int num = sc.nextInt();
		int tot = 0;
		for(; i <= num; i++) {
			tot += i;
			
		}
		
		System.out.println(tot);
		*/
		/*
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수를 입력하세요>");
		int i = sc.nextInt();
		int tot = 0;
		for( ;0< i ; i-- ) {
			tot += i;
		}
		System.out.println(tot);
		*/
		
		// 0을 입력할때 까지 입력받고, 입력받은 모든 총합을 마지막에 출력하세요.
		Scanner sc = new Scanner(System.in);
		
		System.out.println("정수를 입력하세요>");
		
		int tot = 0;
		for(; ; ) {
			int num = sc.nextInt();
			if(num==0) {
			break;	
			}
			tot+= num;
			
			System.out.println(tot);
		}
		
	}
	

}



'P-Language > [Java]' 카테고리의 다른 글

[Java] 6 - 다차원 배열  (0) 2022.06.03
[Java] 5 - 배열  (0) 2022.06.03
[Java] 3 - 연산자, 제어문, 조건문  (0) 2022.06.03
[Java] 2 - 변수와 입,출력문  (0) 2022.06.03
[Java] 1 - 환경 변수와 자바의 기본  (0) 2022.06.03

[day03]

1. 연산자 operator
 
1) 종류 
단항 연산자 : + - (int 타입등) ++ -- !
이항 연산자 : 산술연산자 : + - * / % 
      비교연산자 : <  <= > >= == != (결과 true/false)
      논리연산자 : && || 


삼항 연산자 : ?  :
대입 연산자 : =
복합대입 연산자 : 산술 + 대입 : = += -= *= /= %=
(쉬프트/비트 연산자)

2) 연산자 우선순위 (높은순)
단항연산자 : ++ -- (전위형)
     + - (양수음수)  
     ++ -- (후위형)

형변환 : (타입)
산술연산자 : * / %
   : + - (덧셈뺄셈)
(쉬프트)
비교연산자 : <  <= > >=  instanceof
   : == !=
(비트)
논라연산자 : && (and) 
   : || (or)
삼항연산자 : ?:
복합대입연산자 : = += -= *= /= %= 


2. 제어문 
- 조건문 : if, switch
- 반복문 : While, do-while, for, 업그레이드 for (forEach)
- 보조제어문 : break, continue

break : 강제종료
continue : (반복문에서 주로 사용) 아래 작성된 실행문 건너뛰고 다음 반복으로 넘어간다. 

3. 조건문 if
조건이 참이면 영역안의 코드를 실행

1) 구조 
#1.
if(조건식){
//조건이 참일 경우 실행해야될 코드들 작성

}

조건식 : 비교연산이나 논리연산이 혼합된 식으로 구성한다.
                또는 boolean 타입의 변수가 올 수 있다.
        -> 결과 또는 값이 true/ false가 와야함
영역을 뜻하는 {} 중괄호 기호는 영역안에 들어갈 명령문이 1개면 생략가능

#2.
if(조건식){
//조건이 참일 경우 실행할 코드들
}else {
  //조건이 거짓일 경우 실행할 코드들
}


else : 뒤에 조건식이 안붙고 바로 {} 영역
혼자 사용불가. if와 else의 순서가 바뀌어도 안됨
옵션처럼 반드시 써야되지는 않는다.

#3.
if(조건식1){
//조건식1이 참이면 실행할 코드들
}else if(조건문2){
//조건식2이 참이면 실행할 코드들
}else if(조건문3){
//조건식3이 참이면 실행할 코드들
}else {
// 위의 모든 조건이 거짓일때 실행할 코드들..
}

 

package day03;

public class Test20 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

	

	// 증감 연산자 : ++, --
	// 전위형 : 나 먼저
	// 후위형 : 가장 나중에
	/*
	int a = 10;
	System.out.println(a);
	++a;
	System.out.println(a);
	--a;
	System.out.println(a);
	System.out.println(++a);
	System.out.println(--a);
	*/
		
	int b = 10;
	System.out.println(b);
	System.out.println(b++);
	System.out.println(b);
	}
}

 

 

 

package day03;

public class Test21 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		// 대입연산자 : 대입해야 변수안의 값이 변견된다.
		 /* int a = 10;
		  System.out.println(a+10);
		  System.out.println(a);
		  // a = a + 10
		  
		  int i =5 , j = 5;
		  System.out.println(i++);  // 5
		  System.out.println(++j);  // 6
		  System.out.println(+j); 
		
		  System.out.println("i=" +i+", j=" + j );
		  */
		
		  
		  // 문제 1. 출력결과를 먼저 주석으로 적어보고 실행
		 /*
		  int k = 10;
		  System.out.println(k++); // 10
		  System.out.println(++k); // 12
		  					 ++k;  // 13
		  System.out.println(++k); // 14
		  System.out.println(k++); // 14
		  System.out.println(k);    // 15
		  */
		
		
		  //문제2 r의 결과
		  int a = 10;
		  int b = 10;
		  int r = ++a + ++b;   // 11+ 11 22
		  r = ++a + b++;    
		  //System.out.println(r);// 12 + 11 23
		  r = ++a + a ;     
		  //System.out.println(r);//    // 13 + 13
		  r = ++a + a++ ;     
		  //System.out.println(r);//   // 14 + 14
		
		  r = ++a + ++a ;      //    // 16 + 17
		  System.out.println(r);
				
	}
}

 

package day03;

public class Test22 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		/* 단축키 
		 *  실행 : ctrl + F11 
		 * syso 적고 ctrl + space 
		 * 공백만들기 shift + enter 공백만들기
		 * 한줄복사 : ctrl + alt + 화살표 위/아래
		 * 이동 : alt + 화살표 위/아래
		 * 한줄삭제 : ctrl + D
		 * 맨첫줄로 : Home  / 맨뒷줄로 END
		 * 
		 * */
		
		
		// 사칙연산 : + - * / % (나머지값)
		int a = 10 + 10;
		System.out.println(a);
		int b = 10 % 3 ;   // (나머지 값)
		System.out.println(b);
		
		long l = (long) 100000 * 100000;  // * 100000 은 인트타입이라 long 형변환 해줘야함
		long k = 100000L * 100000;  // * 100000 은 인트타입이라 long 형변환 해줘야함
		System.out.println(l);
		System.out.println(k);

	}
}

 

 

 

package day03;
import java.util.Scanner;

public abstract class Test23 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		
	
		
		/*
		// 문제1. 숫자 2개를 입력받고, 사칙연산 결과를 출력해보세요.
		
		Scanner No1 = new Scanner(System.in);	
			int num1 , num2 ;
		 System.out.println("값 1을 입력하세요 >>");
		/* int num1 = Integer.parseInt(sc.nextLine()); */
		/*num1 = No1.nextInt();
		System.out.println("값 2를 입력하세요 >>");
		/*int num2 = Integer.parseInt(sc.nextLine()); */
		
		/*num2 = No1.nextInt();
		
		System.out.println("덧셈출력값은" + (num1 + num2) + "입니다") ;
		System.out.println("곱셈출력값은" + (num1 * num2) + "입니다");
		System.out.println("뺄셈출력값은" + (num1 - num2) + "입니다");
		System.out.println("나눗셈출력값은" + (num1 / num2) + "입니다");
		*/
		
		
	    
		// 문제2. 초단위로 정수를 입력받고,
	     //         계산된 "??분??초" 형태로 출력해보세요. 
		 
	        
	        Scanner No2 = new Scanner(System.in);
	        System.out.println("초를 입력>> ");
	        int sec = No2.nextInt();
	    	/*int sec = Integer.parseInt(No2.nextLine()); */
	        System.out.println((sec / 60) + "분"  + (sec%60)+ "초" + "입니다"); 
	      
	        No2.close();
		
	
	/*
	     / 문제3. 초단위로 정수를 입력받고, "??시간??분??초" 형태로 출력해보세요.
	   	
	        int sec;
	        Scanner No3 = new Scanner(System.in);
	        System.out.println("초를 입력>> ");
	     sec = No3.nextInt();
	        
	    
	        System.out.println((sec/3600) + "시간" + ((sec%3600)/60)+"분" + (sec%60) +"초");
	       
    */
	        
	      /* 문제4. 최소 화폐 매수 구하기
	                금액을 입력받으면, 최소한의 화폐매수를 구해주는 프로그램 
	          콘솔예시)


	          금액입력 :   67800   <- 사용자가 입력 
	          5만원 : 1장
	          1만원 : 1장
	          5천원 : 1장
	          1천원 : 2장
	          5백원 : 1개
	          1백원 : 3개
	                
		 Scanner No4 = new Scanner(System.in);
		System.out.println("금액을 입력하세요");
	    int money = Integer.parseInt(No4.nextLine());
	    System.out.println("5만원 : "  + (money / 50000) + "장");
	    System.out.println("1만원 : "  + (money % 50000/10000) + "장");
	    System.out.println("5천원 : "  + (money % 10000/5000) + "장");
	    System.out.println("1천원 : "  + (money % 5000/1000) + "장");
	    System.out.println("5백원 : "  + (money % 1000/500) + "장");
	    System.out.println("1천원 : "  + (money % 500/100) + "장");
    */
	     
	}
}
package day03;

public class Test24 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 비교 연산자 : < <= > >= == !=
	int a = 10;
	int b = 5;
	
	int c = a + b ;
	boolean d = a  != b;
	System.out.println(d);
		
		
		// 논리 연산자 : && ||
		// %% : and
		// a && b : a, b 둘다 참이여야 함 
		
		// || : or
		// a || b : a, b 둘중 하나라도 참이면 참

	boolean result = a >= b || a > b  && b > 0; // && 부분을 먼저 연산함  result = a >= b || (a > b  && b > 0)
	System.out.println(result);
	
		// 삼항 연산자 
		// true / false의 결과식 ? 참일때 결과값 : 거짓일때 결과값;
		// a = 10 , b = 5
	

	System.out.println(a < b ? a : b);
 	int res =   a > b ? a : b ;
	char resCh = a > b ? 'O' : 'X' ;
	
	
	}

}
package day03;

public class Test25 {

	public static void main(String[] args) {
// TODO Auto-generated method stub

//	int a = 10;
	//System.out.println(a = a +10);
	 
	//System.out.println(a);
		
		
		// 복합 대입 연산자 : += -= *= /= %=
		int a = 10;
		System.out.println(a);
		a = a + 1; // a += 1; // a++; 같은 말임
		System.out.println(a);
		a += 1;
		System.out.println(a);
		
		a -= 10;   // a = a - 10; 동일함
		a *= 3;    // a = a * 3
		System.out.println(a);
		
		a /= 3;   // a = a / 3 ;
		
		a %= 3; // a = a % 3;
		
		int b = 10;
		int c = 20;
		boolean d = b < c ;
		System.out.println(!d);    // ! : (not 연산자) true / false 값을 반전 시키는 연산자 
	}
}
package day03;
import java.util.Scanner;
public class Test26 {

	public static void main(String[] args) {
	/*
		int a = 20;
		if(a>10) {
			System.out.println("a는 10보다 크다");
			System.out.println("a는 10보다 크다");
			System.out.println("a는 10보다 크다");
			System.out.println("a는 10보다 크다");
			
		}
		// a - 10 하고 10이랑 비교
		// 연산자 우선순위에 따라 산술연산 먼저 계산됨
		
		if(a- 10 < 10) {
			System.out.println("안녕하세요");
			
		}
		
		
		int score = 50;
		if (score >= 60) {
			System.out.println("합격입니다");
		}
		if (score< 60) {
			System.out.println("불합격입니다");
		}
		
		
		if (score >= 60) {
			System.out.println("합격입니다");
		}else {

			System.out.println("불합격 입니다");
			
		System.out.println(score>= 60? "합격" : "불합격");
		}
		*/
		
		
		//문제 : 점수하나를 입력받고
		// 90점 이상이면 "수" 80점 이상이면 "우"
		// 70점 이상이면 " 미" 그 이하는 "재시험" 출력
		
		
		
		Scanner exam = new Scanner(System.in);
				
		System.out.println("점수를 입력하세요 >>");
				//String a = exam.nextLine();
				//int point = Integer.parseInt(a);
				// => int point = Integer.parseInt(sc.nextLine());
		int point = Integer.parseInt(exam.nextLine());
				if(point >= 90) {
					System.out.println("수");
				}else if(point>=80) {
					System.out.println("우");
				}else if(point>=70) {
					System.out.println("미");
				}else {
					System.out.println("재시험");
				}
		
		/*	///if(score > 100{
				System.out.println("점수가 이상해요");
		}else {
				if(score >= 90) {
					System.out.println("수");	
					} else if (score >= 80) {
					System.out.println("우");
					} else {
					System.out.println("재시험");
							
					}
		 						*/	
		exam.close();
	}
}
package day03;
import java.util.Scanner;
	public class Test27 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//* 연산자 문제*
		// 문제1. 정수 두개를 입력 받고, 몫과 나머지를 출력하세요.
		// 문제2. 일(day)수 입력받고, 몇개월 몇일인지 출력해보세요.
		//	단, 한달은 30일로 고정		
		// 문제3. 점수를 3개를 입력받고, 총점과 평균을 구하여 촐력해보세요.
			
		//*if문 문제*
		// 문제4. 숫자하나를 입력받고, "음수"인지 "양수"인주 "0"인지 출력해보세요.
		// 문제5. 1~99 사이 숫자를 입력받고. "짝수" 인지 "홀수"인지 출력해보세요.
		// 문제6. 정수 3개를 입력받고, 3개의 숫자중 가장 큰 수를 출력하세요.
		
		/* 문제 1번		
		Scanner sc = new Scanner(System.in);
		int num1 , num2 ;
		
		System.out.println("값 1을 입력하세요>>");
		num1 = sc.nextInt();
		
		System.out.println("값 2을 입력하세요>>");		
		num2 = sc.nextInt();
		
		System.out.println("몫은" + (num1/num2) + "입니다");
		System.out.println("나머지는" + (num1%num2) + "입니다");
 		*/
		/* 문제 2번
		Scanner sc = new Scanner(System.in);
				System.out.println("숫자를 입력하세요 >>");
				int day = sc.nextInt();
		System.out.println((day/30)+"개월"+(day%30)+"일 입니다.");
		*/
		
		/*
		Scanner sc = new Scanner(System.in);
		int num1 , num2 , num3;
		
		System.out.println("값 1을 입력하세요>>");
		num1 = sc.nextInt();
		
		System.out.println("값 2을 입력하세요>>");
		num2 = sc.nextInt();
		
		System.out.println("값 3을 입력하세요>>");
		num3 = sc.nextInt();
		
		System.out.println("총점은 "+ (num1+num2+num3)+"이고" + "평균은"+((num1+num2+num3)/3)+"입니다");
		*/
		
			//*if문 문제*
			// 문제4. 숫자하나를 입력받고, "음수"인지 "양수"인지 "0"인지 출력해보세요.
			// 문제5. 1~99 사이 숫자를 입력받고. "짝수" 인지 "홀수"인지 출력해보세요.
			// 문제6. 정수 3개를 입력받고, 3개의 숫자중 가장 큰 수를 출력하세요.
		/*
		Scanner sc = new Scanner(System.in);
		System.out.println("숫자 하나를 입력하세요>>");
		int num1 = sc.nextInt();
			if(num1 > 0) {
				System.out.println("양수");
			}else if(num1 < 0){ 
				System.out.println("음수");
			}else if(num1 == 0){
				System.out.println("0");
		    }
		*/
		
	/*
		Scanner sc = new Scanner(System.in)	;
				System.out.println("1 ~ 99 숫자하나를 입력하세요 >>");
		int num1 = sc.nextInt();
		 if(num1 > 0 && num1 < 100){	
			if(num1%2==0) {
				System.out.println("짝수입니다");
				} else 	{	
				System.out.println("홀수입니다");
				}
		}else {
		 System.out.println("1~99 사이의 숫자가 아닙니다");
		 }
	*/
		/*
		Scanner sc = new Scanner(System.in);
		//int num1 , num2 , num3;
		System.out.println("정수 1값을 입력하세요");
		int num1 = sc.nextInt();
		
		System.out.println("정수 2값을 입력하세요");
		int num2 = sc.nextInt();
		
		System.out.println("정수 3값을 입력하세요");
		int num3 = sc.nextInt();
		
		if(num1 > num2) {
			if (num1>num3) {
				System.out.println(num1);
			}else {
				System.out.println(num3);
			}
		}
		else {
			if (num2>num3) {
			System.out.println(num2);
			} 
			else {
			System.out.println(num3);
			}
		}
			
			
			/*
		 * if((num1>num2)&&(num1>num3)) {
		 
			System.out.println("정수 1값이 가장 큰값입니다.");
			}else if((num1>num2)&&(num1<num3)) {
			System.out.println("정수 3값이 가장 큰값입니다.");
			}else if((num1<num2)&&(num1>num3)) {
			System.out.println("정수 2값이 가장 큰값입니다.");
			}else if((num1<num2)&&(num1<num3)) {
			System.out.println("정수 3값이 가장 큰값입니다.");
			}
		
		*/
		
		
		
		/* 문제7. 2차원 평면에서 직사각형은 
        왼쪽 상단 모서리와 오른쪽 하단 모서리 두점으로 표현한다. 
      (100,100) 과 (200, 200) 의 두점으로 이루어진 사각형이 있을때,
      정수 x, y 값을 입력받고 점(x, y)가 이 직사각형안에 
      있는지 판단하는 프로그램을 작성하세요. 
		 */
		
		Scanner sc = new Scanner(System.in);
		int x, y;
		System.out.println("x값을 입력하세요");
		x = sc.nextInt();
		System.out.println("y값을 입력하세요");
		y = sc.nextInt();
		
		//boolean result = ((x > 100 && x < 200) && ( y > 100 && y < 200));
		//if((200 > x > 100 ) && (200 > y > 100)); { 
		//if(result==true) 
		if((x >= 100 && x <= 200) && ( y >= 100 && y <= 200)){ 
			System.out.println("사각형 안에 존재합니다");
		}else {
			System.out.println("존재하지않습니다");
		}
		
		
		sc.close();
		
	
	}
}

'P-Language > [Java]' 카테고리의 다른 글

[Java] 6 - 다차원 배열  (0) 2022.06.03
[Java] 5 - 배열  (0) 2022.06.03
[Java] 4 - 조건문(switch), 반복문  (0) 2022.06.03
[Java] 2 - 변수와 입,출력문  (0) 2022.06.03
[Java] 1 - 환경 변수와 자바의 기본  (0) 2022.06.03

[day 02]

1. 변수의 사용
1) 접미사 :
리터럴값 뒤에 데이터 타입을 명시해주는 방법

2) 기본값 :
boolean : false; 
char    : ''; .'\u0000'; 
int     : 0;
double  : 0.0;
참조열  : null;

2. 출력문 : 콘솔에 출력하는 명령문 : 개발자가 확인용으로 많이 사용
1) 종류
System.out.println();  : 엔터기능 O
System.out.print();    : 엔터기능 X (옆으로 값이 출력)
System.out.printf();   : 엔터기능 X 값을 출력할때 서식문자를 사용해야함 (몰라도 됨)

2) 출력문 내 연산 
숫자 + 숫자 ==> 더한 결과 출력
"문자열" + "문자열" ==> 문자로 연결된 문자열 출력
"문자열" + 숫자 ==>  문자로 연결된 문자열 출력 
'문자' + 숫자 ==> 문자의 아스키코드값 + 숫자 결과값 숫자 출력 


3) 이스케이프 문자 
: 출력문 내에서 사용되며, 어떠한 기능을 가지고 있는 특수 문자
(홑따옴표나 겹따옴표 안에 작성) 

"\n" : 줄바꿈 
"\t" : 탭간격
"\"" : 쌍따옴표 문자로 취급
"\'" : 홑따옴표 문자로 취급
"\\" : 역슬래쉬를 문자로 취급

3. 형변환 Casting, Type Conversiom, Converting
boolean 타입을 제외한 다른 타입들을 변환 시키는 것
(타입)변수 
char < int < long           // float < double

1) 강제형변환 : (다운캐스팅, 디모션) : 큰타입 -> 작은타입 : 형변환 공식 적는다!
int a = 300;
byte b = a; ==> error !!
byte b = (byte)a; ==> 문법적으로 error는 안나지만, 값이 깨짐

double d = 1.5;
int i = (int)d; => i = 1


(int)3.5 + 4 => 7 
(double)4 + 4 = 8.0000000


2) 자동형변환 : (업캐스팅, 프로모션) : 작은타입 -> 큰타입 : 형변환 공식 생략가능 
 
double d = 3.14 * 10; 31.4
   3.14 * 10.0 (int -> double로 자동 변환)

5 + 3.5 ==> 8.5
5 / 2   ==> 2      5 / (double)2 ===> 2.5 
int/int ==> int


4. 입력문
1) Scanner : 자바패키지에서 제공하는 클래스. 입력 받을 때 사용. 

#1. import 문 사용 : 
자바 파일 최상단 package....; 명령문 밑에 작성
import java.util.Scanner;

#2. Scanner 객체 생성 (main 안에 작성) 

Scanner sc= new Scanner(System.in); 

#3. 입력받기 (받고싶은 만큼 메서드 작성)

String 변수 = sc.nextLine(); 

#4. Scanner 객체담기

sc.close();

package day02;

public class Test03 {
	public static void main(String[] args) {
		//변수 선언
		// 타입 변수명;
		int i;
		int a, b;
		i = 10; // i 변수 초기화
		System.out.println(i);
		
		//변수 선언 + 초기화(데이터에 값을 처음 넣는것) 
		int c = 100, d = 200;
		//int e, f = 100; // (이것은 안됨) 
		int abc = 10;
		abc=20;
		System.out.println(abc);
		
		abc = 10 + 20;
		System.out.println(abc);
		
		abc = 10 + 20 * 50 / 100;
		System.out.println(abc);
		// =: 대임연산자 : 대입연산자의 오른편 연산을 모두 마친후 결과를 왼편 변수에 저장한다.
	}
}
package day02; // 현재 파일이 위치한 패키지의 이름을 명시

public class Test04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
			/* public : 접근지정자 : 완전공개 ~ 나중에
			 * Class : 클래스 만들때 사용하는 키워드
			 * 			자바는 클래스들로 구성되어 있다. 자바의 최소단위. 클래스 바깥에는 코드작성 x
			 * Test04 : 클래스 이름 : 첫글자 대문자로 만들어야함 (변수와 구분하기 위해)
			 * 			-> 이클립스에서 파일생성시 Name에 이름작성하면 이것이 클래스 이름이 되고,
			 * 				파일 생성시 첫글자 대문자로 작성.
			 * 			클래스 명명규칙 : 첫글자 대문자, 띄어쓰기x 한글x , 특수기호 _ & 만가능, 키워드x, 대소문자 구분
			 * 			패키지 안에서는 같은 이름의 클래스가 있을 수 없다
			 * 
			 * static : 전역 키워드 (클래스 키워드) : 나중에
			 *			 
			 * void : 리턴타입 중 리턴 할 값 없다!
			 * main : 메서드 이름 public static void main(String[] args) {
			 * 			메인메서드는 프로그램이 시작되면 가장 먼저 자동으로 실행되는 메서드.				
			 * 			메인메서드가 종료되면 프로그램도 종료가 된다.
			 * 			프로그램내에 반드시 하나만 존재해야함.
			 * 
			 * (String[] args): 매개변수 : 나중에
			 * 
			 * 
			 * */
	}
}
package day02;

public class Test05 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		char ch = '\u0051';
		System.out.println(ch);
		
		
		//오버플로우 : 잘못된 형태  byte -128~127
		byte b = (byte)12;
		System.out.println(b);
		
		
		// int : 10 진수 / 8 진수 : 0으로 시작하는 수
	// 			 16진수 : 0x 로 시작하는 수  
		//		 2 진수 : 0b 로 시작하는 수
		int i = 15;     //10진수
		int j = 015;    // 8진수
		int k = 0x15;   //16진수
		int l = 0b0101; //2진수
		//  0    1   0    1
		// 2^3  2^2 2^1  2^0
		
		System.out.println(i);
		System.out.println(j);
		System.out.println(k);
		System.out.println(l);
	
		// 문자열 
		String abc = "안녕하세요";
		System.out.println(abc);
		abc  = "java 재밌어요";
		System.out.println(abc);
		//abc = 'A';
		abc = "A";

	}
}
package day02;

public class Test06 {

	public static void main(String[] args) {

		// 접미사
			//(명시적 형변환)
		int a = 100;
		long l = 100;  // 100L; 과 동일함 
		double d = 3.14;
		float f = 3.14F; // double이 아니라 float 타입이라고 값에 명시
		
		int i; 
	    i = 0;
		
		
		// 출력문 연산
		System.out.println(10 + 3);
		System.out.println("A"+ 10);
		System.out.println("A"+ 10 + 20);
		System.out.println("A" + (10 +20 ));
		System.out.println(10 + 20 + "A");
		System.out.println('A'+10);
		// 아스키코드 숫자 '0' = 48, 'A' = 65, 'a' = 97  
		
		System.out.println("hello \"hello\"");
		
	}
}
package day02;

public class Test07 {

	public static void main(String[] args) {
		// 문제 : 정수형 변수 A 와 B애 각각 10, 20을 대입하고,
		// 값을 서로 교환해서 출력해보세요.
		
		// 변수 생성 + 값 대입하기
		//System.out.println(a + "" + b); // 10  20
		// A 변수의 값과 B변수의 값을 교환해서 저장

		//System.out.println(a + "" + b); // 20  10
		
		int a = 10;
		int b = 20;
		
		System.out.println(a + " " + b); // 10  20
		// A 변수의 값과 B변수의 값을 교환해서 저장
		
		int tmp = a;
		a = b;
		b = tmp;
		System.out.println(a + " " + b); // 20  10
		
	}
}
package day02;

public class Test08 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		char ch = 'A';
		int a = ch;                //자동 형변환
		System.out.println(a);
		
		a = 65;
		char c = (char)a;          //강제 형변환
		System.out.println(c);
		System.out.println(a);
		
		
		int b = 5;
		double d = b;
		System.out.println(d);
		
		double e = 5.7;
		int f = (int)e;
		System.out.println(f);
		
		char g = 'ㄴ';
		double h = g;
		System.out.println(h);
	}
}
package day02;

public class Test09 {

	public static void main(String[] args) {
			byte b = 127;
			int i = 100;
			System.out.println(b+i);  //227
			System.out.println(10/4); //  2
			System.out.println(10.0/4); // 2.5
			System.out.println((byte)(b+i)); // -28
			System.out.println((int)2.9 + 1.8); //3.8
			System.out.println((int)(2.9 + 1.8)); //4
			System.out.println((int)2.9 +(int)1.8); //3
			
	}
}
package day02;


// #1. import 문 작성
import java.util.Scanner;

public class Test10 {

	public static void main(String[] args) {
		// #2. Scanner 객체 생성
		Scanner sc = new Scanner(System.in);
			
		// #3. 입력 받기
		// 사용자가 어떤 입력을 해야하는지 힌트를 줄 메세지 출력
		System.out.println("지금 많이 졸린가요??");
		
		// 입력받아, 받은 값 가져와 msg 변수에 저장
		// (입력받아오는 값의 타입은 무조건 String 타입이다)
		String msg = sc.nextLine();
		System.out.println("타이핑:"+  msg);  //잘 가져왔는지 확인용 출력문
		
		// #4. Scanner 닫기
		sc.close();
		
	} //main
} //class
package day02;

import java.util.Scanner;

public class Test11 {

	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		System.out.println("이름을 입력하세요 >>");
		String name = sc.nextLine();
		System.out.println("당신의 이름은 " +  name  + "입니다");	
		
		System.out.println("나이를 입력해주세요 >>");
		//String age = sc.nextLine();
		//int realAge = Integer.parseInt(age);
		int Age = Integer.parseInt(sc.nextLine());
		
		
		System.out.println("당신의 나이는 " + Age + "살 입니다");
		// 참조형 String과 기본형 타입은 형변환 공식으로 호환 불가능
		// int numAge = (int)age; 안됨
		// String -> int로 변환
		// int 변수명 = Integer.parseInt(String 타입변수or "값");
		
		// String -> double 
		// double 변수 = Double.parseDouble(String 타입변수or "값");
	    
		// String -> float
		// float 변수 = Float.parseFloat(String 타입변수or "값");
		
		// String -> boolean
		// boolean 변수 = Boolean.parseBoolean(String 타입변수or "값");
	
		
		
		System.out.println("당신의 내년 나이는 " + (Age + 1) + "살 입니다");
		
		/* String -> int 
		 * integer.parseInt(String타입변수 or "값"
		 * */
		
		sc.close();
		
	}
}
package day02;
import java.util.Scanner;

public class Test12 {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
			
	
		
		
		System.out.println("이름을 입력하세요 >>");
					//String name = sc.nextLine();
					System.out.println("당신의 이름은 " +  sc.nextLine()  + "입니다");	
		
		System.out.println("나이를 입력해주세요 >>");
			int Age = Integer.parseInt(sc.nextLine());
					System.out.println("내년에는 " + (Age + 1) + "이 겠군요!");
	
					//System.out.println("내년에는 " + (sc.nextInt() + 1) + "이 겠군요!");
		
		System.out.println("당신의 키는 얼마인가요 ? >>");
			double Tall = Double.parseDouble(sc.nextLine());
       				System.out.println("당신의 키는 대략 " + ((int)Tall + 1) +"이 겠군요");
		
       		
       	System.out.println("당신의 전화번호는 무엇입니까? >> ");
       				//String num = sc.nextLine();
       				System.out.println("당신의 번호는 " +  sc.nextLine()  + "입니다");	
		
       		
       				
		sc.close();
	}

}

 

'P-Language > [Java]' 카테고리의 다른 글

[Java] 6 - 다차원 배열  (0) 2022.06.03
[Java] 5 - 배열  (0) 2022.06.03
[Java] 4 - 조건문(switch), 반복문  (0) 2022.06.03
[Java] 3 - 연산자, 제어문, 조건문  (0) 2022.06.03
[Java] 1 - 환경 변수와 자바의 기본  (0) 2022.06.03

환경변수 세팅하는 이유?

- 자바파일 위치(경로)에 상관없이 실행하기위해서 

 

세팅방법은?

 

 

 

 

 

package day01;

public class Test01 {

	public static void main(String[] args) {
	// 한줄 주석
		
	/* 여러줄 주석
	 * 
	 * 실행 단축키 ctrl + F11
	 * */
		System.out.println("hello!!!");
	}
}
package day01;

public class Test02 {
	public static void main(String[] args) {
		// 변수 선언
		boolean b;
		char ch;
		int i;
		double d;

		int a, c;
		//같은 int 타입의 변수 두개 한번에 만들기.
		
		// 변수 선언만하고 값을 대입안한 후 출력하면 에러발생!!
		//System.out.println();
		/*
		b = false;
		System.out.println(b);
		b = true;
		System.out.println(b);
		*/
		
			
		/* 데이터 bit < byte < KB MB GB TB PB EB ZB YB
		 * 기본형 8가지
		 * 논리형 boolean true or false  1byte 
		 * 문자열 char                   2byte
		 * 숫자열 4가지
  		 *      - byte   1    -128~ 127
  		 *      - short  2     -3200~ 3200
  		 *      - int    4     -21억 ~ 21억
   		 *      - long   8
   		 *      
   		 *       실수형 - float   4 byte   8자리
   		 *              - double  8 byte   16자리
		 */   
	 

		ch='한';

		System.out.println(ch);
		i = 1000;
		System.out.println(i);
		d= 3.988778;
		System.out.println(d);
		
		// 문자열 변수 선언
		String test; 
		test = "javajava";  
		
		System.out.println(test);
		
	}
}

'P-Language > [Java]' 카테고리의 다른 글

[Java] 6 - 다차원 배열  (0) 2022.06.03
[Java] 5 - 배열  (0) 2022.06.03
[Java] 4 - 조건문(switch), 반복문  (0) 2022.06.03
[Java] 3 - 연산자, 제어문, 조건문  (0) 2022.06.03
[Java] 2 - 변수와 입,출력문  (0) 2022.06.03

저번 시간에 이어서 남은 몇 가지 태그를 이어가자.

 

<Form 태그>

@ form

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <!-- 폼 관련 태그 
   사용자가 웹사이트로 정보를 보낼 수 있는 요소들을 폼이라고 한다.
   
   - form 태그
        <form 속성 ="값"...> 여러 폼 요소 태그... </form>
   - form 태그 속성
       action : 사용자가 입력한 내용을 서버쪽으로 보내 처리해줄때
               서버에서 사용할 경로
       method : 사용자가 입력한 내용들을 서버쪽으로 어떻게 넘겨줄지 전송 방식 지정
              get : 브라우저 주소창에 사용자가 입력한 내용이 그대로 드러남
              post : 입력내용이 주소창에 드러나지 않고 내부에 담아 전송. 길이제한
               
       name   : 폼태그에 이름 붙혀주는 속성. form 태그 여러개면 구분하기 위해.
       target : action에 지정한 경로를 현재 창이 아닌 다른 위치에 열도록 지정
       autocomplete : 자동완성기능 
       
       
    - input 태그
            : 홑태그로 폼태그 안에서 사용자가 입력하는 부분을 만들때 주로 사용   
            한줄 글자, 체크박스, 로그인 버튼등 여러 타입이 존재
            
            * type 속성의 속성값
            text : 한줄짜리 텍스트 입력할 수 있는 텍스트 상자
            hidden : 화면상에는 보이지 않지만, 서버로 전송할때 함께 숨겨서 전송하고 싶을때 사용
            value속성으로 넘길 값도 작성해주어야함!!
            
            password : 비밀번호 입력함. 작성한 내용이 *. 으로 표시됨
            radio : name 속성으로 묶어서 한개의 항목만 선택하게 할때 사용
            Checkbox : 두개 이상의 여러가지 선택 가능
            color : 색상 선택 상자
            date, month, week : 날짜(년,월,일), 월 년, 주 년 선택
            reset : 입력된 모든 정보 초기화. value에 지정한 값이 버튼에 표시됨.
            submit : 사용자가 입력한 정보를 서버로 전송시키는 버튼. value에 지정한것이 버튼에 표기.
            image : 이미지 버튼. submit과 같은 기능 src 속성 기입
            file : 파일 첨부시 (웹에서 자세히)
            
     *input의 다른 속성
        autofocous : 입력 커서 자동으로 표시되게
        placeholder : 입력박스에 기입할 내용 힌트로 표시
        readonly : 읽기전용
        required : 필수 기입 요소로 지정
        
        min, max, step : 최대값, 최소값, 간격 (숫자 조건)
        size, minlength, maxlengrg : 길이, 최소길이, 최대길이 (텍스트 관련 조건)           
   --> 
    
       <form action="html08_action.html" method="get"> 
				<!-- action에 지정한 폴더로 정보가 감   -->
       <input type="text" name="txt" value="haha" /> <br />
       <input type="hidden" name="hiddenVal" value="10" /> <br />
       <input type="password" name="pw" /> <br />
       <input type="radio" name="subject" checked/> java <br />
       <input type="radio" name="subject" /> jsp <br />
       <input type="radio" name="subject" /> SPRING <br />
       <input type="checkbox" name="css" checked value="css" /> css <br/>
       <input type="checkbox" name="js" value="js" /> js <br/>
       <input type="color" name="col" />
       <input type="date" name="date" />
       <input type="month" name="mon" />
       <input type="week" name="wk" />
       <input type="time" name="time" />
       <input type="datetime-local" name="local" />
       <input type="reset" value="reset" />
       <input type="image" src="img/tayo.jpg" width="30%"/>
       <input type="button" value="새창열기" onclick="window.open()" /> <br />
       <input type="file" name="upload" />
       
       <input type="submit" value="검색" />
   
   
    </form>
   
    
</body>
</html>

 

내용이 긴데 코드를 사진으로 보자면 

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <form>
       <input type="text" name="txt" autofocus/> <br />
       <input type="text" name="txt2" placeholder="yyyy-mm-dd" /> <br />
       <input type="text" name="txt3" readonly value="읽기전용"/>  <br />
       <input type="text" name="txt4" required /> <br />
       <input type="submit" value="submit" />
       
   </form>
   
   
</body>
</html>
```

 

 

 

 


<옵션 선택 태그>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <!-- 옵션중에 선택하는 태그 : selet -->
   <form>
     
      <select name="opt">
          <option value="1" selected>내용1 </option>
          <option value="2"> 내용2</option>
          <option value="3"> 내용3</option>
          <option value="4"> 내용4</option>
          
          
      </select>
      <br />
      <!-- 여러줄 입력하는 텍스트 영역-->
      <textarea cols="20" rows="5" name="txt"> 안녕하세요</textarea>
      <!-- 버튼 태그 -->
      <button type="button" onclick="alert('hello')">전송</button>
      
    </form>
   
   
    
</body>
</html>


 

<앵커 만들기>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <h1> 앵커 만들기 </h1>
   <ul id="menu">
        <li><a href="#content1" >메뉴1</a> </li>
        <li><a href="#content2" >메뉴2</a> </li>
        <li><a href="#content3" >메뉴3</a> </li>
         
   </ul>
   <h2 id="content1">내용1</h2>
   <p>
       Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, 
ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum
 molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem 
ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.
       
       
   </p>
   <a href="#menu">메뉴로 돌아가기</a>
   
   <h2 id="content2">내용2</h2>
    <p>
       Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, 
ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum 
molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, 
consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur 
iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos 
dolorum sapiente? Et cum veniam quod.
       
       
   </p>
   <a href="#menu">메뉴로 돌아가기</a>
   <h2 id="content3">내용3</h2>
    <p>
       Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, 
ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum
 molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, 
consectetur adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur
 iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos 
dolorum sapiente? Et cum veniam quod.Lorem ipsum dolor sit amet, consectetur 
adipisicing elit. Illo, quam, ab omnis accusamus itaque consequuntur 
iste necessitatibus inventore magnam harum molestias veniam nam, dignissimos 
dolorum sapiente? Et cum veniam quod.
       
       
   </p>
   <a href="#menu">메뉴로 돌아가기</a>
   
    
</body>
</html>

 

 

 

 

 


 

<head 부분 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>안녕</title>
    <meta name="description" content="문서에 대한 설명" />
    <meta name="keywords" content="검색시 걸리게 해줄 키워드 나열," />
    <meta name="author" content="사이트, html 문서 작성자" />
    <meta name="viewport" content="width=device-width, initial-scale=2.0, user-scalable=no, maximum-scale=1.0, minimum-scale=1.0 " />
    <!-- 렌더링 설정, 호환성 문제가 주로 발생되는 IE(자체 랜더링엔진 사용하면 결과물이 달라지거나 동작이 안되는 경우가 많음) 때문에 표준모드로 렌더링 되도록 설정 -->
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <!-- 외부 데이터나 문서를 가져오기 위한 태그-->
    <link rel="icon" href="img/tayo.jpg"/>
    <link rel="stylesheet" href="css파일의 경로" />
    <style>
    /* css 코드 작성 : html요소에 디자인 적용 */
    </style>
    <script src="javascript 파일경로" type="text/javascript"></script>
    
</head>
<body>
   
   
   
   <script>
       // javascript 작성
    </script>
   
    
</body>
</html>

 

<시멘틱 태그>

  시멘틱 태그 : 웹 페이지의 각 요소에 의미를 부여해서 의미와 관련성을 기반으로     보다 진보된 검색 또는 서비스가 가능하도록 시도
      html5에서는 시멘틱 웹을 위한 태그들이 제공됨.
      안써도 무방하나 웹표준에 맞추려면 쓰는것도
      
     header : 헤더, 상단부, 로고 같은것 
     nav    : 네비게이션 (메뉴 바)
    aside   : 오른쪽 소메뉴 같은 용도
    section : 본문 부분. article 포함
    article : 본문의 주 내용 컨텐츠가 들어가는 부분
    footer  : 하단부. 회사 소개, 회사 정보, 사이트 맵 등

'WEB Creator > [HTML]' 카테고리의 다른 글

[HTML] 1 - brackets를 활용한 html 기본 + 태그 몇개  (0) 2022.06.01
[HTML] OT  (0) 2022.06.01

https://brackets.io/ 에서 다운로드

 

1. ! tab 키를 누르면

2. <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
</body>
</html>

과 같이 변하게 된다.

간단하게 설명을 하자면,
<!DOCTYPE html> <!-- 문서 유형을 지정하는 선언문. html5 문서이다  -->

<!-- 웹 문서의 시작과 끝을 알려주는 태그 : 안에는 크게 head와 body로 나뉜다.  -->
<html lang="en"> 

 <!-- head : 브라우저에게 정보를 주는 태그
         화면에 보이지 않지만 브라우저가 알아야할 정보를 모두 이 안에 태그로 입력
        title, meta, style, link...   -->
<head>
   
   <!--meta : 문자 인코딩 및 문서 키워드, 요약정보  -->
    <meta charset="UTF-8">
    
    <!-- 웹 브라우저 탭에 작성되는 제목 표시줄 지정  -->
    <title>Document</title>
</head>

<!-- body : 실제 브라우저에 표시될 내용들, 안에 작성 -->
<body>
    <h1>
        안녕하세요~~
    </h1>
    
    
</body>
</html>

 


 

태그 알아보기

<텍스트 관련 태그>

@ h태그 (제목 태그)

<body>
    <!-- 텍스트 관련 태그 -->
    <!-- h: 제목태그 -->
    <h1> 제목태그</h1>
    <h2> 제목태그</h2>    
    <h3> 제목태그</h3>
    <h4> 제목태그</h4>
    <h5> 제목태그</h5>

h1 → h5 갈수록 글자가 작아진다.

 

 

@ p태그

 <!-- p : 단락만들기 : 앞뒤 줄바꿈 기능이 있는 텍스트 덩어리 -->
     p태그는 paragraph의 앞글자를 딴 것으로 글자그대로 문단을 뜻합니다
 

  <p>Lorem ipsum dolor sit amet, //Lorem 치고 tab 누르면 글자나옴
   <br /> br은 한줄내리기
   consectetur adipisicing elit. Architecto iusto omnis officiis porro nisi ducimus 
   repellendus minima sapiente tempora, delectus dolor modi temporibus voluptate non 
   et libero ea ex consectetur!</p>
   
   <pre>        pre 입력한 그대로 나옴 띄워쓰기 여러개 표시가능
   </pre>
   
	</p>

 

@ hr / span / strong / u

<hr /> hr 가로줄 테그
 
   <blockquote>
    blockquote 인용문   Lorem ipsum dolor sit amet,
   </blockquote>
   
  <span style="color: red"> span 텍스트를 묶어주는 태그 </span> 
   <strong> strong 굵게나옴 </strong> 
   <u> u는 밑줄을 나오게함 </u>

<태그> </태그> 가 한 쌍이다.


 

 

<목록 태그>

@ ul / ol

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   
   
   <!-- 목록 태그 :
    ul : 순서가 없는 목록 만들기 : unorder list : ul 안에 목록은 li 태그 안에 나열
        각 항목안에 원이나 사각형 같은 불릿(bullet)이 붙는다.
        CSS의 list-style-type 속성으로 수정가능
    ol : 순서가 있는 목록 만들기 : ol안에 목록은 li 태그로 나열
         각 항목앞에 순서를 나타내는 숫자, 문자가 붙는다. 
         트개 속성으로 수정 가능
         type 속성 : 목록앞에 숫자/ 영문/ 로마숫자로 변경가능.
          값: 1= 숫자(default), a = 영문소문자, A = 영문대문자,
             i = 로마숫자 소문자, I= 로마숫자 대문자
             
             
         
         start 속성 : 시작값 지정
        reversed : 항목을 역순으로 표시
       -->
<h2> 웹개발 커리큘럼</h2>
   <h3>ul, li</h3>
   <ul>
     Ul> li*5 tab키 누르면 자동으로 만들어줌  
       <li> java </li>
       <li> html css </li>
       <li> javascript </li>
       <li> jsp </li>
       <li> spring </li>
       
   </ul>
   
   
   <ol typr ="1" reversed>  
       <li> java </li>
       <li> html css </li>
       <li> javascript </li>
       <li> jsp </li>
       <li> spring </li>
       
   </ol>
    
</body>
</html>

 


<표 만들기 태그>

@ table

   tr : 행을 지정 (가로 줄, row). <th></th>  개수로 가로줄이 몇개인지 알 수 있다
   td : 셀 만들기 (세로한칸) <th></th>안에 몇개의 셀이 들어갈것인가 ?
   th : 제목 셀

 

<th></th>를   먼저세우고 td를 넣음

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
   <!-- 표 만드는 태그
   
   table 은 행(row)과 열(column) 으로 이루어져 있다.
   table : 테이블의 영역을 묶는 태그
   tr : 행을 지정 (가로 줄, row)
   td : 셀 만들기 (세로한칸)
   th : 제목 셀
   
   table 태그 안에 행의 수만큼 <tr> 태그를 넣고
   각 tr태그 안에 열의 수만큼 td 태그를 만든다.
   
   
   행/열 합치기
   : 셀을 합치는 것이므로 td에 적용
       colspan 속성 : 열 합치기 colspan = "합칠 열의 개수"
       rowspan 속성 : 행 합치기 rowspan = "합칠 행의 개수"
   -->
   
   <table border = "1">
       <tr> 가로
           <td rowspan="2"> 1행 1열</td>
           <td> 1행 2열</td>
           <td> 1행 3열</td>
       </tr>
       
       <tr> 
        
           <td colspan="2"> 2행 2열</td>
       </tr>
    
   </table>

      <table border = "1">
       <tr> 가로
           <td rowspan="2"> 1행 1열</td>
           <td> 1행 2열</td>
           <td> 1행 3열</td>
       </tr>
       
       <tr> 
           <td> 2행 1열</td>
           <td colspan="2"> 2행 2열</td>
       </tr>
    
   </table>
    
</body>
</html>

 

 


<a 태그>

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    
    <!-- 링크 : a태그 : href속성을 이용하여 다른 페이지로 넘어가게 할 수 있는 태그
        - 속성 
            href   : 링크 주소 
            target : 링크한 내용이 표시될 위치
                        새창 : _blank
                        현재창 : _self(default)
                        
                                        
        - 앵커 
            <태그 id="앵커명"> ... </태그>
            <a href="#앵커명"> 텍스트나 이미지 </a>
    
    
    -->
    <a href="http://naver.com"> 네이버로 이동 </a>
    <a href="http://naver.com" target="_blank"> 네이버 새창 이동 </a>
    
    
    
    
</body>
</html>

<이미지 태그>

@ img

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <!--
      - 이미지 파일
        GIF : 색상수 256가지, 파일크기 작음. 
            아이콘, 불릿, favicon(작은이미지), 움짤
        JPG : 사진. 
        PNG : 투명 배경 가능.
        
        
       - 속성
           src : 이미 경로 값으로 지정(필수 기입 속성)
           alt : 이미지 설명글 저장
    
        - 경로
            상대 경로 : 현재 작업파일을 기준으로 이미지 파일의 위치 작성
            
                    / \ : 한단계 안으로 들어가기
                    .  : 현재위치
                    .. : 한단계 위로 나가기
            절대 경로 : 이미지 파일이 저장된 컴퓨터 내의 위치한 전체 주소
                        C:\html\img\test.jpg
      -->
   
   <h2> img tag</h2>
   <img src="tayo.jpg" width="50%"/>      <!--(같은 경로, 디렉토리)  --> 
   <img src="E:\htmlcss\workspace\html\img\tayo.jpg"/>     <!--절대경로 --> 
   <img src= "img/tayo.jpg" width="200"/>    <!--img/로 한단계 안으로   --> 
   <img src="../mickey%20png.png" width="30%">   <!--../ 을 적어서 한단계 위로  --> 

</body>
</html>

 


 

 

'WEB Creator > [HTML]' 카테고리의 다른 글

[HTML] 2 - html 폼관련 태그 + 옵션 태그 + 앵커  (0) 2022.06.01
[HTML] OT  (0) 2022.06.01

[HTML]

1.  HTML
: HyperText Markup Languege : 웹에서 사용하는 웹문서

확장자명 : .html
일반문서 : 예) 엑셀 : 입력프로그램과 내용 확인하는 프로그램이 동일
웹문서   : 장성 프로그램 " 웹 편집기", 문서 보는 프로그램을 "웹 브라우저"로 서로 다름.

웹표준   : 웹 사이트를 만들때 지켜야하는 약속들을 정리한 것.
HTML5

웹 접근성 : 청각장애인, 시각장애인등 환경적 제한이 있는 사용자를 고려하여
웹페이지를 작성하는 기법.
정식인증은 비쌈 자가 진단 테스트 정도 해볼 수 있는 사이트 : 
https://accessibility.kr/

W3C : 웹 창시자 ( 팀 버너스 리) 가 W3C(World wide web Consortium) 단체 설립.
웹 표준을 제정하는 단체
HTML5는 HWATWG(애플, 모질라, 오페라) + W3C가 작성

2. IDE Intergrated Development Environment : 통합 개발 환경
개발할때 사용하는 개발 툴

brackets.io

3. 태그
: 마크업할 때 사용하는 약속된 표기법
- <> 을 이용해 태그로 표시 : <html><head><img>
- 태그는 소문자로 작성 : 대소문자 구분하지 않지만 HTML5 표준명세에서 소문자 권장함.
- 여는 태그와 닫는 태그 정확히
태그 : 쌍으로 이루어짐 <html>....</html>,<h1>....</h1>
홀태그 : 하나의 태그로 이루어짐<img />, <br />
- 들여쓰기
- 태그는 속성과 함께 작성 가능
<태그명 속성명 ="값" 속성명="값".... >....</태그명> (쉽표 x)

4. 유용한 사이트
www.w3schools.com /듀토리얼 싸이트
https://developer.mozilla.org/ko/
https://caniuse.com/

5. HTML 문서 구조
주석 : <!-- html 주석 -->

5. 적용 스타일

1) 폰트 변경
font-family : 브라우저 사용자의 시스템에 설치 되어있지 않거나
운영체제에 따라 원하는 결과가 안나올 경우가 있다.
@font-face  : 웹 폰트 사용. 웹 문서 안에 끌꼴 정보도 저장하여, 사용자가 접속하면 
사용자 시스템에 글꼴 다운로드시켜 적용
font-size   : 클자 크기 지정 : px | em | rem | ex | pt 단위로 지정가능
font - weight : 글자 굵기 지정 : normla | bold | border | lighter
 100   200  400 400이 normal
font - style : nomal | italic | oblique 

2) 텍스트 스타일
color : 글자색 지정. 색상명 | rgb(0,256,0) | #00f
text-decoration : 텍스트에 줄 표시 지정. none | underline | overline | line-through

3) 문단 스타일
text-align : 텍스트 정렬 left | right | center | justify..

4) 목록과 링크 스타일
list-style-type : 목록의 불릿과 번호  스타일 지정
none | disc | circle | square 
none | 1 | a | A....
5) 색상과 배경
background-color : 배경색 지정
background-image : 배경이미지, url('이미지파일경로') 로 이미지 지정
background-attachment : 배경이미지 고정. scroll(default) | fixed
* background : 속성값만 나열하여 한번에 적용



* css 크기 단위
px : 화소 단위, 해상도에 따라 상대적인 크기를 가짐
% : 백분율, 기정사이즈를 기반으로 상대적인 비율의 크기를 가짐
em : 배수 단위, 지정 사이즈를 기반으로 배수로 계산된 크기를 가짐.
16px -> 2em (32px)을 말함 : 중첩태그의 경우 바로 상위 태그의 값을 기준으로 
배수가 괴어 주의가 필요함. 
rem : root em 으로, 최상위 요소 사이즈를 기준으로 함. 배수 단위 
16px -> 1rem = 16px, 2rem = 32px, 1.5rem ->24px....

* css 색상표현 단위
1) 색상이름 표기 : https://www.w3schools.com/colors/colors_names.asp
2) 16진수 표기 :#ffffff 같이표기/ #fffff -> #fff 같은값반복이면 생략가능
                   #22FF55 ->#2F5 
# 8A  2B  E2
  빨  녹  파  / 각 두자리가 16진수의 빨녹파 값
3) RGB표기 : rgb(120,43,68)
4) RGBA 표기 : rgba(12,44,67,0.5) RGB+alpha (투명도) 0.0-> 투명
투명도 지정 속석 opacity : CSS제공 속성. 상속함
rgba는 상속안함


6. 박스모델
1) 블록 레벨 : 요소 하나가 혼자 한 줄 다 차지하는 요소. 박스형태
p, h, ul, ol, div, form, table 등
2) 인라인 레벨 : 혼자 한줄 차지하지 않는 요소
img, br, span, input, textarea, button 등
3) display : 화면 배치 방법 결정
none : 화면에 표시 하지 않음
block : 블록 레벨로 지정
inline : 인라인 레벨로 지정. 한 줄로 배치 가능한데, 너비나 높이, 
마진 같은 박스 모델값이 정확히 적용 안될 수 도 있다.
inline-block : 인라인 레벨요소이면서 블록레벨 속성을 갖도록 지정하는 것
4) border : 테두리
border-width, border-color 등 속석이 분리 적용하게 있다.
간단하게는 border : 두께 스타일 색상와 같이 한번에 적용가능.
그 외 border-top/-left/-right/-bottom, border-top-left-radius

5) 여백
margin : 요소의 바깥 여백
값 1개 : 상하좌우, 값 2개 : 상하 좌우, 값 4개 : 상 우 하 좌
padding : 콘텐츠와 테두리 사이 여백, margin과 적용방법 같음

'WEB Creator > [CSS]' 카테고리의 다른 글

[CSS] 9 - Flexbox  (0) 2022.06.07
[CSS] 8 - media query 미디어쿼리  (0) 2022.06.07
[CSS] 7 - 포지셔닝  (0) 2022.06.07
[CSS] 2 - 선택자  (0) 2022.05.31
[CSS] 1 - 개념과 적용 방법  (0) 2022.05.31

4. **선택자 Selector** (웹 크롤링할때 필요함)

--- HTML 네이밍 해줄 수 있는 속성---
태그명
name 속성 : form안에 input태그에 기술해서 데이터 넘길때 많이 사용.
이름 붙히는 느낌 (css에서 다른 속성을 더 많이 사용)
class 속성 : 다른 태그들과 값이 같아도 된다 -> 그루핑 역할 해줄때 사용
id 속성 : 문서내에서 유일한 값을 가져야함. 태그에 아이디 부여(사람= 주민번호)

1) 전체 선택자 : * 
     모든 요소에 스타일 적용
    * { 속성명 : 값;...} 

 

2) 태그 선택자 : 태그명
       해당 태그에 모두 적용
       태그명 { 속성명 : 값;...}


3) *class 선택자*  : .class속성값 
         특정 부분에 스타일 적용. class 속성값이 동일한 태그들에 적용 
         그룹처럼 지정해서 적용할때 사용. 
         <h1 class="hello">...
         .hello { 속성명: 값; ...}  


4) id 선택자 : #아이디속성값
        특정 태그에(요소)에 스타일 적용.
        id 값은 문서내에서 유일해야하므로 유일한 특정 한개의 요소에만 적용 할 때 사용.
        <h2 id="test">...
         #test { 속성명 : 값;....}

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSS</title>
    <style>    
       * {margin: 10; padding: 0}     /* 1) 전체선택자 */
        h1 {color: red;}	/* 2) 태그 선택자 */
        p{color: blue}
        .lorem{color: grey; font-size: 30px} /* 3) 클래스 선택자 */
        #container{			 /* 4) ID 선택자 */
            background-color: turquoise;
            width: 300px;
            height : 200px;
            margin: 0 auto;
        }
    </style>
</head>
<body>
   <h1> Hello HTML   </h1>
    <h1> Hello CSS </h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum cupiditate eum reiciendis possimus? Voluptates similique repellat, dolore architecto veniam, vel placeat tenetur! Repellat facere aperiam porro quod saepe accusamus qui?
    </p>
    <p class="lorem">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum cupiditate eum reiciendis possimus? Voluptates similique repellat, dolore architecto veniam, vel placeat tenetur! Repellat facere aperiam porro quod saepe accusamus qui?
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum cupiditate eum reiciendis possimus? Voluptates similique repellat, dolore architecto veniam, vel placeat tenetur! Repellat facere aperiam porro quod saepe accusamus qui?
    </p>
    <p class="lorem">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum cupiditate eum reiciendis possimus? Voluptates similique repellat, dolore architecto veniam, vel placeat tenetur! Repellat facere aperiam porro quod saepe accusamus qui?
    </p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorum cupiditate eum reiciendis possimus? Voluptates similique repellat, dolore architecto veniam, vel placeat tenetur! Repellat facere aperiam porro quod saepe accusamus qui?
    </p>
</body>
</html>


5) 여러 선택자 동시 적용
: 쉼표를 구분자로 나열하여 적용

선택자, 선택자 {...}

6) 스타일 적용 우선순위
          1) 인라인 스타일 > id스타일 > class 스타일> 태그 스타일
          2) 코드 순서 : 나중에 기술한것이 적용
         *스타일 상속 : 부모 태그에 적용된것은 자식 태그도 적용됨.
          ex) body 태그에 폰트적용하면 그 안에 있는 태그들도 모두 적용

7) 연결 선택자
      - 하위 선택자 : 띄어쓰기 구분자로 선택자 나열
        상위 선택자 하위선택자 {...}

- 자식 선택자 : >를 구분자로 하위 요소 전체가 아니라 바로 아래 자식요소만 적용
부모선택자 > 자식선택자 {...}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selector</title>
    <style>
       #container > ul{border: 1px solid red;}  /*  > 를 사용하여 바로 아래자식인 ui에게 만 사용 */
    </style>
        
</head>
<body>
   <div id="container">
       <h1>Hello CSS in container</h1>
       <ul>						<!-- 여기에만 적용됨 -->
           <li> list1
               <ul>					<!-- 여기는 적용 안됨 -->
                   <li>list1-1</li>
                   <li>list1-2</li>    
                   
               </ul>
           </li>
           <li>      list2
               <ul>					<!-- 여기도 적용 안됨 -->
                   <li>list2-1</li>
                   <li>list2-2</li>
                   <li>list2-3</li>
                   <li>list2-4</li>

               </ul>
           </li>
       </ul>
       
   </div>
</body>
</html>


- 인접 형제 선택자 : +를 구분자로 기술. 가장 가까운 형제 요소. 
선택자 + 선택자 {...}
(형)  (아랫동생)
- 형제 선택자 : ~을 구분자로 기술. 인접과 달리 형 다음에 붙은 모든 형제 요소에 적용.
선택자 ~ 선택자 {...}
(형) ~   (동생들) 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selector</title>
    <style>
      h1+ul{color: blue; font-weight: bold;}    /*  + 를 사용하여 h1 과 가장가까운 형제에게만 적용 */ 
    </style>
        
</head>
<body>
  <ul>
    <li>list1-1</li>
    <li>list1-2</li>
</ul>
<h1>Hello CSS</h1>                         <!--h1이 여기 있으니 그 바로 밑 형제들만 적용됨 -->
    <li>list2-1</li>
    <li>list2-2</li>
    
</ul>
<ul>
    <li>list3-1</li>
    <li>list3-2</li>
    <li>list3-2</li>
    
    
</ul>
</body>
</html>

h1이 2-1 위에 있을때
h1이 1-1 위에 있을때
선택자 ~ 를 사용했을때 h1~ul



8) 속성 선택자
- 속성명 : 지정한 속성을 가진 요소 찾아 적용
선택자[속성]{...}
p[class]
- 속성값 : 속성명에서 나가아 속성의 값이 일치하는 요소를 찾아 적용
선택자[속성 = 값]{...}
p[class=hello]
- 속성^=값 : 특정 값으로 시작하는 속성을 가진 요소
선택자[속성^=값]{...}
p[class^=A]
- 속성$=값 : 특정값으로 끝나는 속성을 가진 요소
선택자[속성$=값]{...}
- 속성*=값 : 특정값을 포함하는 속성을 가진 요소
선택자[속성*=값{...}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selector</title>
    <style>
 
        ul{list-style: none;}
        li{display: inline; margin: 10px;}
        a{text-decoration: none; font-size: 30px; }
        a[href] {background-color: yellow;}
        a[target= "_blank"]{background-color: turquoise;}   /* target = _blank 인 */   
        a[class^="j"]{background-color: yellow;}			/* j로 시작하는 */
        a[class$="a"]{background-color: yellow;}			/* a로 끝나는 */
        a[class*="s"]{background-color: yellow;}			/* s가 포함된 */
    
    </style>
</head>
<body>
<ul>
    <li> Main menu :</li>
    <li><a href="http://naver.com" class="java">naver</a></li> 
    <li><a href="http://google.com"class="jsp">google</a></li>
    <li><a href="http://daum.net" class="spring">daum</a></li>
</ul>


</body>
</html>



9) 가상클래스 선택자
: 사용자 동작에 반응하는 스타일 적용시 사용
a 태그에서 많이 볼 수 있다.

a:link  : 기본. 방문전 링크 스타일에 적용
a:visited   : 방문한 링크 스타일에 적용
a:hover : 요소가 마우스 커서를 올려놓을때 스타일
a:acitve : 요소가 활성화 했을때 스타일 적용 (a-> 누르고 있을때)
a:foucs : 요소가 초점이 맞추어 져있을때 스타일 적용)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Selector</title>
    <style>
 
        a:link{color: black;}
        a:visited{color: turquoise;}
        a:hover{background-color: yellow;}
        a:active{color: magenta;}
        a:focus{background-color: lightblue;}
    </style>
</head>
<body>
<ul>
    <li> Main menu :</li>
    <li><a href="http://naver.com" class="java">naver</a></li> 
    <li><a href="http://google.com"class="jsp">google</a></li>
    <li><a href="http://daum.net" class="spring">daum</a></li>
</ul>


</body>
</html>


10) UI 요소 상태에 따른 가상 클래스 선택자
: 웹 요소 상태에 따라 스타일 지정

: enable  : 사용가능상태의 요소 (텍스트 필드)
: disable : 사용불가상태 요소
: checked : 체크된 상태의 요소 (라디오, 체크박스)

11) 구조 가상 클래스 선택자
: 웹 문서 구조를 기준으로 특정 위치에 있는 요소 찾아 스타일 적용

: root : HTML
: nth-child(n)      : 앞에서부터 n번째 자식요소
: nth-last-child(n)  : 뒤에서부터 n번째 자식요소
: nth-child(odd)  : 홀수번째 자식요소
: nth-child(even) : 짝수번째 자식요소
: first-child  : 첫번째 자식
: last-child : 마지막 자식
: not(선택자) : 괄호안에 있는 요소를 제외한 나머지

12) 가상 요소 선택자
가상 클래사 = 여러 태그중 원하는 태그를 선택하기 위한 선택자
가상 요소  = 태그안 내용의 일부분만 선택해 스타일 적용

::first-line : 첫번째 줄
::first-letter : 첫번째 글자
::befor : 내용 맨 앞
::after : 내용 맨 뒤

'WEB Creator > [CSS]' 카테고리의 다른 글

[CSS] 9 - Flexbox  (0) 2022.06.07
[CSS] 8 - media query 미디어쿼리  (0) 2022.06.07
[CSS] 7 - 포지셔닝  (0) 2022.06.07
[CSS] 3 - 적용 스타일과 박스 모델  (0) 2022.05.31
[CSS] 1 - 개념과 적용 방법  (0) 2022.05.31

[CSS]

1. CSS (Cascading Style Sheets)
HTML과 함께 웹 표준의 기본 개념.
HTML : 웹 사이트 내용 나열
CSS : 디자인 구성
독립적 사용불가. HTML에 도움을 주는 언어.

2. 스타일 형식 
*선택자* {속성명 : 속성값; 속성명 : 속성값; ....}
선택자  : Selector라 하며, 스타일을 어디에 적용할 것인지 선택하는 방법 (중요)
{}  : 스타일 적용 코드 영역
:   : 속성명과 값의 구분자
;   : CSS 속성 : 값 지정후 명령어의 종료를 나타내기위해 기입.

주석  : /* 내용... */

3. CSS 적용 방법 3가지
스타일 규칙들을 한데 묶어 놓은것을 '스타일 시트'라 함.

 

1) *외부 스타일 시트* : CSS 파일(.css)을 별도로 작업하여 연결
     <link href="css 파일 경로" rel="stylesheet" /> type="text/css (//MIME TYPE)" />

     href : css 파일 경로 지정
     rel : 링크 걸린 파일과의 관계에 대한 기술
     type : 파일의 형식 기술 : text로 기술된 css 타입의 파일이다 (MIME Type)

2) 내부 스타일 시트 : HTML 파일에 <style> 태그로 작업
3) 인라인 스타일 시트 : 태그에 속성으로 작업

 

/* stylr.css 파일 */
h1 {background-color: aqua;}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Styletype</title>
    <!-- 외부 스타일 시트 -->
    <link href="style.css" rel="stylesheet" type="text/css" />
    <style>
        /* 내부 스타일 시트 : 이 태그 사이에 CSS 문법으로 스타일 코드 작성  */
        h2{background-color: lightblue;}
    
    
    </style>
</head>
<body>
     <h1> 외부스타일 시트 </h1>
     <h2> 내부스타일 시트 </h2>
     <h3 style="background-color: magenta"> 인라인 스타일 시트 </h3>
    
    
    
</body>
</html>

 

'WEB Creator > [CSS]' 카테고리의 다른 글

[CSS] 9 - Flexbox  (0) 2022.06.07
[CSS] 8 - media query 미디어쿼리  (0) 2022.06.07
[CSS] 7 - 포지셔닝  (0) 2022.06.07
[CSS] 3 - 적용 스타일과 박스 모델  (0) 2022.05.31
[CSS] 2 - 선택자  (0) 2022.05.31

+ Recent posts