Jam's story

3일차 본문

Java

3일차

애플쩀 2022. 2. 17. 17:21

자동형변환 -> 작은 ->큰

 강제형변환 -> 큰->작은

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		String name;
		System.out.println("이름입력");
		name=br.readLine();
		System.out.println("이름은:"+name);

 

	int kor, eng, mat;
		double avg;
		short sum;
		System.out.println("국어점수를입력하세요 ");
		kor=Byte.parseByte(br.readLine());
		System.out.println("영어점수를입력하세요 ");
		eng=Byte.parseByte(br.readLine());
		System.out.println("수학점수를입력하세요 ");
		mat=Byte.parseByte(br.readLine());
		
		sum=(short)(kor+eng+mat);
		avg=(double)sum/3;
		System.out.printf("총점은 : %d, 평균은 : %f", sum,avg);

 

cast연산자는 같은 숫자형일때만 형변환 가능, 클래스들간의 형변환 할때도 사용한다 

package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오전 7:36:34
 * @subject 자료형( Data Type )
 * @content  48/72
 *                    1. 에러 메시지 : Duplicate local variable temp
 *                    정리 요약
 */
public class Ex01 {

public static void main(String[] args) {

int $number;  //  _  $ 만 특수문자 사용가능하다. 


int x = 1, y = 2;

{
//int temp;  // temp 변수 선언,   초기화 X
// 에러 메시지 : Duplicate local variable temp
// int temp = x;  // temp 변수 또 선언 + x값으로 초기화
int temp = x;  // temp 변수 또 선언 + x값으로 초기화
x = y;
y = temp;
}

System.out.println(x+", " + y);

} // main

} // class

package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오전 10:32:11
 * @subject
 * @content
 *                    1. 질문 풀이
 *                    2. 질문 풀이
 */
public class Ex02 {

    public static void main(String[] args) {
       
        /* 질문설명
        String name = "홍길동";
        // 이름은 "홍길동"입니다.
        //               '/"'  제어문자
        //               '\n'
        System.out.printf("이름은 \"%s\"입니다.", name);
        */      
       
        // 함세강                                     1바이트( byte )       -128~127              
        // 246  2진수 변환 ->        [0][][][][][][][][0] [1][1][1][1] [0][1][1][0]
        // *** 산술 오버플로워 발생 ***
       
        // byte b = (byte) 246;
        // System.out.println( b );  // -10    산술 오버플로워 발생  잘못된 값.

 
package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오전 10:46:00
 * @subject  p 48 실수의 진법 변환
 * @content
 */
public class Ex03 {

    public static void main(String[] args) {
        // 3.       실수
        // 3.0     실수
        // 3.625 실수    -> 메모리상 저장 [2진수  0/1]        
        // 3 ->  11
        //  0.625 ->   [1][0][1]
        // 0.625 * 2 = [1].25
        // 0.25   * 2 = [0].5
        // 0.5     * 2 = [1].0
        // 종료
       
        // 3.625 ->                 11.1        01   float/double 자료형 저장 어떻게 ?
        //                                   2^-1  + ...
       
        // 11:00    시작
        // 오차 있는 자료형
        // float 4 / double 8   배정도 정밀도               - 부동소수점 표기
        //         32              64
        // float      1(S) 8(E 지수)  23(M 가수)
        // double   1(S) 11(E 지수)  52(M 가수)
       
        // 예) 10진수 예 - 지수/가수
        // 1234.567
        //  1.2345678 *10^3
        // 1.2345678E3
        // 2진수 진법변환
        // 3.625
        // 11.101
        // 1.1101E1           +127         == 128
       
       
        // 0.14      
        // 0.141592  정밀한 숫자
        // [0][1][0]0][1] ......                             ....  무한
       

        // 키 , 몸무게  저장할 변수   175.3 65.2  
        float height;
        // 에러메시지 : Type mismatch: cannot convert from double to float
        //                    타입 불일치        :  
        //   f    =    d       같은 실수형
        height = 175.3F;  // 접미사 F , f
        System.out.println( height );
 
        // 에러메시지 : Type mismatch: cannot convert from int to byte
        //   b   =   int
        // byte b = 500 ;
        // long l = 1000;
        // int  i = l;
       
        double weight = 65D;  // 정수 int
       
        // 65D == 65d == 65.0
       
        /*
        // double -> float
        0.0   [][][][][][][][]
        0.0F [][][][]
        // int  L/l 접미사 -> long
        0L   [][][][][][][][]
        0     [][][][]
        */

    }

}

package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오전 11:46:27
 * @subject
 * @content
 */
public class Ex04 {

    public static void main(String[] args) {
        // [시험]
        // 한 학생의 이름, 국어, 영어, 수학, 총점, 평균을 출력...
        String name;
        byte kor, eng, mat;
        short tot; // 0 ~ 300
        double avg; // 평균은 소숫점 2자리
       
        // 표준 입력
        name = "홍길동";
        kor = 35;
        eng = 44;
        mat = 73;
        //총점 : 152   평균 : 50.666666666...........
        //  +            /
       
        // 에러메시지 : Type mismatch: cannot convert from int to short
        //  s  =            int
        //      = 대입연산자
        //           우측항 연산      byte+byte=> byte + byte => byte    int  ?
        // 이유 ? int 보다 작은 자료형은 CPU 연산할 때  처리단위 int 처리
        //                    int
        //           short + byte => int
        //           short + short => int
        //           byte + byte    => int
        // 자동 형변환 X -> 강제형변환
        //                    int
        // tot    =   (short)kor + eng + mat;    // Ex04_02.java
        tot    =   (short)(kor + eng + mat);
        // 12:03 시작
        avg = (double)tot / 3;         // short / int -> int  강제형변환
       
        System.out.printf("국어:%d\n영어:%d\n수학:%d\n총점 : %d, 평균 :  %f\n"
                , kor, eng, mat,  tot, avg);
        /*
        국어:35
        영어:44
        수학:73
        총점 : 152, 평균 :  50.666667
        */
    }

}



package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 12:04:37
 * @subject  형(Type)변환 설명  p74  [시험]
 * @content Type mismatch: cannot convert from int to short
 *
 *                   cast 연산자를 사용해서 강제 형변환...
 */
public class Ex04_02 {

    public static void main(String[] args) {
        /* [시험]
         *  1. 형 변환
         *     ㄱ. 자동 형변환  2가지
         *            1) 작은 자료형의 값을 큰 자료형에 대입할때 자동형변환된다.
         *                    long l = 100;
         *            2) 작은 자료형 연산 큰 자료형 -> 큰 자료형  자동형변환........
         *                   300L + 100  
         *     ㄴ. 강제 형변환
         *             int tot = 152;
         *             double avg = (double)tot/3;       // 50.6666667
         * */

        // ㄴ. 강제 형변환
         //float, double :  %f
        int tot = 152;
        //                    int  연산 double => double
        // double avg = tot / 3.0 ;  // 50                       // 50.6666667
        //  개발자 강제로   int -> double 형 변환 필요
        double avg = (double)tot / 3 ;  // 50                       // 50.6666667
       
        System.out.printf("총점 : %d, 평균 :  %f\n", tot, avg);
        // 총점 : 152, 평균 :  50.000000
        // 총점 : 152, 평균 :  50.666667
       
       
        /*
        // 2) 자동 형변환되는  두 번째 경우
        int a = 100;
        long b = 100;  // 자동 형변환 1 경우
       
        long c = b + a;  // long b + int a
       
        System.out.println( c );
        */
       
        /*
        // 1) 자동 형변환되는  첫 번째 경우
        int i = 100;         // 4
        long j = 10L;       // 8
       
        // long j = int i  자동형변환 O
        j = i;
        */
       
       
       
        // +  덧셈연산자                  2+3+5
        // +  문자연결연산자             "이름은 : " + "홍길동" + "입니다"
       
       
        // 연산자 우선 순위가 있다.           *    >  +
        // () 최우선연산자                   2*( 3+5 )
        // (변환하고자 하는 타입) cast 연산자                     tot / 3
    } //

} //


package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 12:38:54
 * @subject   상수(constant)와 리터럴(literal) p30
 * @content
 */
public class Ex05 {

    public static void main(String[] args) {
        //  상수  ? 고정된 수  +  저장 공간                  <-> 변수
        //  리터럴 ? 고정된 수    3.14     ,  'A',   10 , true 등등   값 자체         ( 상수 )
       
        // 도형 코딩..:  면적, 둘레
        // 원면적 :  반지름 * 반지름 * PI( 3.14)
        // 원둘레 :  2 * 반지름 * PI( 원주율 )
       
        int r = 12;
       
        // pi 상수
        // 상수 선언 할때 대문자 권장
        // 상수명      firstName             FIRST_NAME           MAX_VALUE ( 권장 )
        final double PI = 3.141592;
       
        // The final local variable PI cannot be assigned.
        // It must be blank and not using a compound assignment
        // PI = 3.142592;
       
       
        /* 무수히 많은 PI를 사용(코딩)
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        r * r * pi ;
        */
       
       
        // pi = 3.142592;  X

    }

}
package days03;

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

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 12:51:38
 * @subject   [오후수업]
 * @content
 */
public class Ex06 {
   
    public static void main(String[] args) throws IOException {
        // 표준 입력장치( 키보드 )로 부터 입력받아서 출력.
        // 한줄 코딩 암기
       
        // [키보드]     -> System.in 입력스트림 -> InputStreamReader 클래스 -> BufferedReader 클래스
        //     A                    0100 0001                         'A' 'B'                                        "[A][B][C]"
        //   "ABC"
       
        // Chapter 15 입출력(IO)
        // 자바 언어 : 모든 입력, 출력( Input/Output   == IO )은  스트림(Stream )
        // 스트림 2가지 종류 : 텍스트(문자) 스트림, 바이트 스트림
        // System.in 입력스트림은 바이트 스트림   h -> 문자코드 65
        // 0100 0001       65       ->      A
        BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
        // Scanner 클래스 ,  Console 클래스
       
        // br 변수를 통해서 읽기 작업을 하면 키보드로 부터 입력한 값을 읽을 수 있다....
        // [주의]
        // import java.io.BufferedReader;               import문이 있어야 된다.
        // import java.io.InputStreamReader;
       
        // 이클립스 단축키 :  Ctrl + Shift + O
        // 필요한 모든 import 구문 자동 완성 된다.
        // [대화상자]  java.io.BufferedReader, java.test.BufferedReader 선택
       
        String name ;
       
        System.out.print("> 이름을 입력하세요 ? "); // _홍길동 엔터      
       
        // 메서드 3가지 ?  기능, 매개변수, 리턴값    null / String( 리턴자료형)
       
        // Chapter 08 예외( Exception )  == 에러
        // 에러메시지 : Unhandled exception type IOException
        //                   IO예외를 처리되지 않았다.
        // [암기]
        name = br.readLine();  // read 읽기+Line 한 라인           [블러킹]
         
       
        System.out.printf("이름은 %s입니다." , name);
       
    } // main

} // class
 
package days03;

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

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 2:38:40
 * @subject
 * @content
 */
public class Ex06_02 {

    public static void main(String[] args) throws IOException {
        // [코딩하면서 암기]
        BufferedReader br  = new BufferedReader(new InputStreamReader(System.in));
        String name ;
        System.out.print("> 이름을 입력하세요 ? ");  
        name = br.readLine();  
        System.out.printf("이름은 %s입니다." , name);
    } // main

}
 
package days03;

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

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 3:00:30
 * @subject
 * @content
 */
public class Ex07 {

    public static void main(String[] args) throws IOException {
        // Ex04.java 파일 참조해서 코딩.
        // [시험]
        // 키보드로 부터 이름, 국어,영어,수학 점수를 입력받아서
        /*
         * 국어:35
         * 영어:44
         * 수학:73
         * 총점 : 152, 평균 : 50.666667
         */
       
        // 1. 변수 선언
        String name;
        byte kor, eng, mat;
        short tot;  
        double avg;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        // 2.
        System.out.print("> 이름 입력 ? ");
        name = br.readLine();
        System.out.print("> 국어 입력 ? ");
        // Type mismatch: cannot convert from String to byte
        //   byte =  String
        // (문제 원인/해결)       String "90" -> byte  형변환
        //                               (변환하고자 하는 자료형) cast 연산자를 사용해서 강제 형변환
        //  kor = (byte)br.readLine();  X  왜 () X
        // kor = br.readLine();
       
        // String("90")               -> byte   Byte.parseByte("90");
        // String("90")               -> int     Integer.parseInt("90");
        // String("90")               -> double     Double.parseDouble("90");
        //                                             :
        //String  jumsu = br.readLine();    // "90"
        //kor =  Byte.parseByte(jumsu);    //  90 형변환      
        kor =  Byte.parseByte(   br.readLine()   );    
       
        System.out.print("> 영어 입력 ? ");
        eng =  Byte.parseByte(   br.readLine()   );    
       
        System.out.print("> 수학 입력 ? ");
        mat =  Byte.parseByte(   br.readLine()   );    
       
        tot  =   (short)(kor + eng + mat);  
        avg = (double)tot / 3;  
       
        // 3. 출력
        System.out.printf(
                "이름 : %s\n국어 : %d\n영어 : %d\n수학 : %d\n총점 : %d, 평균 :  %f\n"
                , name, kor, eng, mat,tot, avg);
         
        // Ex07_02.java

    } // main

} // class


package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 3:42:24
 * @subject
 * @content
 */
public class Ex07_02 {

    public static void main(String[] args) {
        // [복습]
        // 이름,국,영,수 키보드 입력
        // 총점,평균 계산
        // 출력
       

    } // main

} // class
 
package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 4:00:13
 * @subject     래퍼(Wrapper) 클래스 [시험]
 * @content
 */
public class Ex08 {

    public static void main(String[] args) {
       
        // [시험]
        // int kor = (int)"90";            d -> i    i -> d
        // cast 연산자는 같은 숫자형일때 만 형변 환가능
        //   ㄴ  클래스들간의 형변환할 때도 사용한다.  UpCasting/DownCasting
       
       
        // 래퍼클래스란? 기본형을 사용하기 쉽도록  기능(메서드,필드)을 구현해 ( 포장해 ) 놓은 클래스
        // int i = 2147483647;
       
        // 기본형 int ==> Integer 클래스
        /*
         * int i = Integer.MAX_VALUE ;
         * System.out.println(  i  );
         */
       
         //  byte -> Byte
        byte b = Byte.MAX_VALUE;
        System.out.println( b );
       
        // char    -> Character *
        // byte    -> Byte                         XXX.parseXXX( "90")  
        // short   ->  Short
        // int       ->  Integer    *              Integer.parseInt( "90")
        // long     -> Long
        // float    -> Float                        Float.parseFloat( "90")
        // double -> Double                     Double.parseDouble( "90")
        // boolean -> Boolean
       
        int i = Integer.parseInt("90");
        double d = Double.parseDouble("90.34");
       

    } // main

} // class



package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 4:16:29
 * @subject       p86 연산자 ( operator )
 * @content
 */
public class Ex09 {

    public static void main(String[] args) {
        // 1. 연산자( operator ) 정의 ? 연산을 수행하는 기호.    +  ;   ,  ()  {} 등등
        // 2. 덧셈 연산자      3 +  5
        //     피연산자( operand ) ?  연산자의 작업 대상( 변수, 상수, 리터럴, 수식 )
        // 3. 연산자 종류
        //         [ 기능 ]
        //    ㄱ. 산술 연산자       +  -  *   /   %        Ex09_02.java
        //     ㄴ. 비교     "                                       Ex09_03.java
        //     ㄷ. 논리     "      
        //               1) 일반논리연산자 :     &&   ||    !           Ex09_04.java    p120
        // ------------------------------------------------------------
        //               2) 비트논리연산자 :   ~    &    |    ^
        //     ㄹ. 대입     "
        //     ㅁ. 기타
        //     ㅂ. 쉬프트 연산자     >>  <<  >>>
         
        //      [피연산자의 갯수]
        //     ㄱ. 단항 연산자
        //      ㄴ. 이항   "         +
        //      ㄷ. 삼항   "

    }

}












package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 4:39:24
 * @subject   산술연산자 설명
 * @content  주의 ) /  % 연산자
 *                      정수 / 0 에러
 *                      실수 / 0  Infinity
 *                      정수 % 0 에러
 *                      실수 % 0  NaN
 */
public class Ex09_02 {

    public static void main(String[] args) {
        // 산술연산자 설명
        int x = 3;
        System.out.println(   x + 5  );  // 덧셈 연산자    8
        System.out.println(   x - 5  );  // 뺄셈 연산자   -2
        System.out.println(   x * 5  );  // 곱셈 연산자     15
        // ( 주의 )  /     %
        //System.out.println(   x / 5  );  // 나눗셈 연산자   0          int / int = int  정수
        //System.out.println(   x % 5  );  // 나머지 연산자   3          int / int = int  정수

        // [시험]
        // java.lang.ArithmeticException: / by zero 정수를 0으로 나눌때 발생
        //                산술적예외(오류,에러)
        // System.out.println(   x / 0  );  // 런타임(실행) 오류          정수 / 0
       
        // Infinity  무한대 리터럴
        // System.out.println(   3.14 / 0  );  // 런타임(실행) 오류       실수 / 0
       
        // java.lang.ArithmeticException: / by zero
        // System.out.println(   x % 0  );          
        // NaN 리터럴                Not a Number == NaN
        System.out.println(   3.14 % 0  );  //  실수 % 0  \
package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 4:39:14
 * @subject
 * @content
 */
public class Ex09_03 {

    public static void main(String[] args) {
        // [비교 연산자]     >     <     >=   <=   == ( 같다)          !=( 다르다 )
        //                   결과는 true/false 논리형
        System.out.println(  3 > 5 );   // false
        System.out.println(  3 < 5 );   // true
        System.out.println(  3 >= 5 );   // false
        System.out.println(  3 <= 5 );   // true
       
        // (주의)
        // 1. 같다 비교 연산자     ==
        int x = 3;
        System.out.println(  x = 5 );   // false
        // !=                  =!  위에 코딩처럼 완전히 다른 의미
        //
        System.out.println(  3 != 5 );   // true

    }

}
         
             
    }

}





package days03;

/**
 * @author kenik
 * @date 2022. 2. 17. - 오후 4:58:58
 * @subject
 * @content
 */
public class Ex09_04 {

    public static void main(String[] args) {
        // [시험]
        //  1) 일반논리연산자 :     &&   ||    !             p114
        /*
         *           ㄱ. &&  일반 논리 AND 연산자(논리곱)
         *                      t && t -> t          피연산자 모두 true 일때만  true 결과이다.
         *                      t && f -> f
         *                      f && t -> f
         *                      f && f -> f
         *          
         *           ㄴ. ||     일반 논리 OR 연산자(논리합)
         *                      t || t     -> t        피연산자 중에 하나만 true 이면  true 결과이다.      
         *                      t || f     -> t            
         *                      f || t     -> t            
         *                      f || f     -> f            
         *          
         *           ㄷ.  !     부정연산자 == not 연산자
         *          
         *                        참을 부정하면 거짓이되고
         *                        거짓을 부정하면 참이된다.
         *                        
         *                        !true    -> false
         *                        !false   -> true
         *                        
         * */
       
        System.out.println(   5 > 3   );  // true
       
        // p91  연산자 우선 순위
        // ***  비교연산자 보다   부정! 연산자 우선 순위가 높아서
        //  ! 피연산자가    5 int 정수값이 왔다..      
        // The operator ! is undefined for the argument type(s) int
        System.out.println(   !(5 > 3)   );  // true
       
        /*
        System.out.println(  3<5 &&   100>2 );  // true
        System.out.println(  3>5 &&   100>2 );  // false
        System.out.println(  3>5 ||   100>2 );  // true
        */

    }

}



































       
    }

}







'Java' 카테고리의 다른 글

8일차  (0) 2022.02.24
7일차  (0) 2022.02.23
5일차  (0) 2022.02.21
4일차  (0) 2022.02.18
2일차  (0) 2022.02.16
Comments