2021.01.21 국비교육 13일차

[TOC]

short circuit operation

  • && 연산자와 ||연산자는 사오항에 따라서 첫번째 항만 체크하고 논리값을 얻는다.
  • &&은 첫번째항이 F면 무조건 F를 반환한다.
  • ||은 첫번째항이 T면 무조건 T를 반환한다.
  • NullPointerException 에러 -> 객체가 잘 생성되지 않았을 때 주로 발생
public class Ex03_8 {

    public static void main(String[] args) {

        String name = null;
        System.out.println( (4 < 2) && (name.length() == 4));
        System.out.println( (4 > 2) && (name.length() == 4)); -- 오류발생

        System.out.println( (4 < 2) || (name.length() == 4)); -- 오류발생
        System.out.println( (4 > 2) || (name.length() == 4));

        //오류 NullPointerException

    }
}

3항 연산자

  • 변수 = (조건식)? 값1 : 값2 ;
  • 조건식이 true면 값 1을 변수에 저장하고 false면 값2를 변수에 저장
public class Ex03_9 {

    public static void main(String[] args) {


        int num = 10;
        String result = ( num > 0) ? "큼" : " 작음";

        int a = 20;
        int b =10;
        int c = 30;

//        int max = ( a > b ) ? a: b;
//        max = ( max > c) ? max : c;

        //int max = ( a > b ) ? a : (b > c) ? b : c; 숫자 바꾸면 결과값 달라짐  
        int max = ( a> b ) ? ((a>c)? a:c) : ((b>c)? b:c);

        System.out.println("최대값은 " + max);

    }

}

Scanner

import java.util.Scanner;

public class ScannerTest {

    public static void main(String[] args) {

    System.out.println("이름을 입력하세요");    
    Scanner scan = new Scanner(System.in); // 콘솔입력사용 객체 생성
    String name = scan.next(); // 콘솔의 입력 내용을 문자열로 가져옴
    System.out.println("입력하신 이름은 " + name);

    //scan.close(); // 닫아줘야함

    System.out.println("나이를 입력하세요");
    int age = scan.nextInt(); //입력내용 : 문자열 --> 정수로 변환
    System.out.println("입력하신 나이는 : " +age);

    scan.close();

    }

}
import java.util.Scanner;

public class ScannerTest4 {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("숫자를 입력하세요");

        int number = scan.nextInt();

        boolean result = number % 2 == 0;

        String message = (result) ? "짝수입니다." : "홀수입니다.";
        System.err.println(message);

    }
}

문자열 정리

public class StringTest2 {

    public static void main(String[] args) {

        String z = String.valueOf(true); // "true"
        String z2 = String.valueOf(10);  //"10"
        String z3 = String.valueOf(3.24F);
        String z4 = String.valueOf(new char[] {'A','B'});
        String z5 = String.valueOf(4.5D);
        String z6 = String.valueOf(125L);
        System.out.println(z);
        System.out.println(z2);
        System.out.println(z3);
         System.out.println(z4);
        System.out.println(z5);
        System.out.println(z6);

        //문자열 조작 함수(trim, length)
        String t = "  hEllo   ";
        System.out.println(t.length());
        System.out.println(t.trim().length());

        //String클래스의 메소드 사용법
        String xyz = "helloworld";
        char[]xyz2 = xyz.toCharArray();
        for(int i =0; i < xyz2.length; i++) {
            System.out.println(xyz2[i]);
        }

        //substring함수
        String q = xyz.substring(3); // 3부터 끝까지
        String q2 = xyz.substring(3, 7); //  3부터 7까지
        System.out.println(q);
        System.out.println(q2);

        //문자열에서 특점운자를 기준으로 나누는 작업
        String msg = "홍길동/이순신/유관순";

        String [] n = msg.split("/");
        System.out.println(n[0]);
        System.out.println(n[1]);
        System.out.println(n[2]);

        System.out.println(n.length);

        for(int i =0; i < n.length; i++) {
            System.out.println(n[i]);
        }

        //charAt(자리수) : 자리수에 해당 문자를 가져옴, 0부터 시작
          String s =  "hello";
        char x = s.charAt(0);
        System.out.println(x);
        System.out.println(s.charAt(1));

        String x2 = s.concat("world");
        System.out.println(x2);
        System.out.println(s);


        //equals
        String aaa = "Hello";
        String aa2 = "hello";

        boolean result = aaa.equals(aa2); // 대소문자 구별 비교
        System.out.println(result);

        boolean result2 = aaa.equalsIgnoreCase(aa2); // 대소문자 구별 x
        System.out.println(result2);

        //contains("문자열") : 지정한 문자열이 포함되어 있는지 boolean리턴
        String s = "hello";

        boolean kkk = s.contains("h");
        System.out.println(kkk);

        boolean kkk2 = s.contains("hx");
        System.out.println(kkk2);


        //endsWith("문자열") : 끝이 지정한 문자열로 끝나는지
        boolean kkk3 = s.endsWith("o");
        System.out.println(kkk3);

        boolean kkk4 = s.endsWith("lo");
        System.out.println(kkk4);

        //startsWith("문자열") : 끝이 지정한 문자열로 끝나는지
        boolean kkk5 = s.startsWith("h");
        System.out.println(kkk5);

        //문자열 만들기
        String ppp = String.format("%s, %d", "홍길동", 20);
        System.out.println(ppp);


        //indexOf("문자열") 지정 문자열 위치
        int index = "hello".indexOf("a");
        System.out.println(index); // 없는 경우 -1

        System.out.println("".isEmpty()); // boolean 결과값
        System.out.println("".length()); //길이


        //replace("A", "B") : A=>B로 변경
        System.out.println("abaca".replace('a', 'A'));
        System.out.println("abc".replace("ab", "xxx"));

        //소문자, 대문자 변경
        System.out.println("abc".toUpperCase());
        System.out.println("ABC".toLowerCase());


    }
}

실행문, 비실행문

단일 if문

public class IFTest {

    public static void main(String[] args) {

        //1. 단일 if문
        System.out.println("문장1");
        int num = 0;
        if(3==3) {
            num = 10;
            System.out.println("문장2");
            System.out.println("문장2-1");
        }
        System.out.println(num);
        System.out.println("문장3");


        //2. 단일 if문 // 홀짝 확인
        System.out.println("-----------------------");

        int num2=100;
        int result = num2%2;
        String msg = "홀수";
        if(result ==0) {
            msg = "짝수";
        }
        System.out.println(msg);


        //3. 단일 if문 // 대소문자 확인
        System.out.println("-----------------------");
        char c = 'A';
        String msg2 = "대문자";
        if('a' <= c && c <= 'z') {

            msg2 = "소문자";
        }
        System.out.println(msg2);
        System.out.println("main종료---------------");

    }

}

IF ELSE

public class IFTest2 {

    public static void main(String[] args) {

        //1. 단일 if문
        System.out.println("문장1");
        int num = 0;
        if(3==3) {
            num = 10;
            System.out.println("참");
            System.out.println("참2");
            System.out.println(num);
        } else {
            System.out.println("거짓");
            System.out.println("거짓2");
        }


        System.out.println(num);
        System.out.println("문장3");


        //2. 단일 if문
        System.out.println("-----------------------");

        int num2=100;
        int result = num2%2;
        String msg;
        if(result ==0) {
            msg = "짝수";
        } else {
            msg = "홀수";
        }

        System.out.println(msg);


        //3. 단일 if문
        System.out.println("-----------------------");
        char c = 'A';
        String msg2;
        if('a' <= c && c <= 'z') {

            msg2 = "소문자";
        } else {
            msg2 = "대문자";
        }
        System.out.println(msg2);
        System.out.println("main종료---------------");


    }

}

다중 if _ else문

import java.util.Scanner;

public class IFTest3 {

    public static void main(String[] args) {

        // 2. 다중 if ~else문
        System.out.println("점수를 입력하시오");
        Scanner scan = new Scanner(System.in);

        int num = scan.nextInt();
        if (num > 90) {
            System.out.println("A");
        } else if (num >= 80) {
            System.out.println("B");
        } else if (num > 70) {
            System.out.println("C");
        } else {
            System.out.println("F");
        }
        scan.close();

        // 콘솔에서 숫자 하나 입력
        // 위의 예제 반대 순서로 만들기

        if (num < 70) {
            System.out.println("F");
        } else if (num < 80) {
            System.out.println("C");
        } else if (num > 90) {
            System.out.println("B");
        } else {
            System.out.println("A");
        }
        scan.close();

    }

}

Switch문

public class SwitchTest {

    public static void main(String[] args) {

        // 3. switch문 ctrl + shift + F -> 자동들여쓰기

        int num = 30;

        switch (num) {
        case 10 : 
            System.out.println("10");
            break;

        case 20 : 
            System.out.println("20");
            break;

        case 30 : 
            System.out.println("30");
            break;

        case 40 : 
            System.out.println("40");
            break;

        default : System.out.println("default");
        }

        System.out.println("종료");

        String xxx = "A";
        switch (xxx) {
        case "A":
            System.out.println("A");
            break;
        case "A2":
            System.out.println("A2");
            break;
        case "A3":
            System.out.println("A3");
            break;
        case "A4":
            System.out.println("A4");
            break;
        default:
            System.out.println("default");
            break;
        }

        char xxx2 = 'A';
        switch (xxx2) {
        case 'A':
            System.out.println("A");
            break;
        case 'B':
            System.out.println("A2");
            break;
        case 'C':
            System.out.println("A3");
            break;
        case 'D':
            System.out.println("A4");
            break;
        default:
            System.out.println("default");
            break;
        }

    }

}

while

public class whileTest {

    public static void main(String[] args) {
        //1부터 10까지
        int n =1;
        while (n <= 10) {
            System.out.println(n);
            n++;
        }
        //10부터 0까지
        while (n > 0) {
            System.out.println(n);
            n--;
        }

        System.out.println("while문 탈출");
    }

}
public class whileTest2 {

    public static void main(String[] args) {
        // 0부터 10까지 합
        int n = 0;
        int sum = 0;
        while (n <= 10) {
            sum += n;
            n++;
        }
        System.out.println(sum);


        //10부터 0까지 합
        int n2 = 10;
        int sum2 = 0;
        while (n2 > 0) {
            sum2 += n2;
            n2--;
        }

        System.out.println(sum2);

        //0부터 10까지 짝수의 합

        int n3 = 0;
        int sum3 =0;
        while (n3 <= 10){
            if (n3 % 2 == 0) {
                sum3 += n3;
            }
            n3++;
        }
        System.out.println(sum3);

        //0부터 10까지 홀수의 합

        int n4 = 0;
        int sum4 =0;
        while (n4 <= 10){
            if (n4 % 2 == 1) {
                sum4 += n4;
            }
            n4++;
        }
        System.out.println(sum4);
    }

}

do-while

public class whileTest3 {

    public static void main(String[] args) {

        //1부터 10까지 출력
        int n = 1;
        while (n < 11) {
            System.out.println("hello" + n);
            n++;
        }

        // 1부터 4까지 출력
        int n2 =1;
        do {
            System.out.println("world" + n2);
            n2++;
        }while (n2 < 5);

        //do - while 1~100 까지 총합
        int n3 = 1;
        int sum3 = 0;
        do {
            sum3 += n3;
            n3 ++;
        }while (n3 < 101);

        System.out.println(sum3);

        //1부터 100까지 3의 배수가 아닌 값들만 더하기
        int n4 = 1;
        int sum4 = 0;

        do{
            if( n4%3 != 0){
                sum4 += n4;
            }
            n4++;
        }while(n4 < 101);

        System.out.println(sum4);

        //3의배수 합, 3의배수가 아닌것들의 합 따로 구해서 더하기
        int n5 = 1;
        int three = 0;
        int notThree =0;

        do{
            if( n5%3 != 0){
                notThree += n5;
            }else {
                three += n5;
            }

            n5++;
        }while(n5 < 101);

        System.out.println(three);
        System.out.println(notThree);

    }
}

+ Recent posts