public class RefDemo1 {
    public static void main(String[] args) {

        int[] a = {10, 30, 40, 100};
        int[] b = a;
        System.out.println("a[0] -> " + a[0]);
        System.out.println("b[0] -> " + b[0]);

        b[0] = 300;
        System.out.println("a[0] -> " + a[0]);
        System.out.println("b[0] -> " + b[0]);

        b = null;
        System.out.println("a[0] -> " + a[0]);
        System.out.println("b[0] -> " + b[0]);
    }
}
​

 

public class RefDemo2 {
    public static void main(String[] args) {
        int[] numbers = new int[3];
        double[] scores = new double[5];
        String[] names = new String[3];

        System.out.println(numbers[0]);
        System.out.println(scores[0]);
        System.out.println(names[0]);

    }
}​

 

public class ArrayDemo1 {
    public static void main(String[] args) {
        // 여러개의 데이터를 단일한 이름으로 관리 -- 배열
        int[] numbers = {10, 14, 20, 3, 15};
        
        /*
        System.out.println(numbers[0]);
        System.out.println(numbers[1]);
        System.out.println(numbers[2]);
        System.out.println(numbers[3]);
        System.out.println(numbers[4]);
        */
        /*
        for (int x=0; x<=4; x++) {
            System.out.println(numbers[x]);
        }
        */

        for (int a : numbers) { // for (배열의 아이템을 담을 그릇 : 반복 처리할 배열) {} 인핸스드 for문
            System.out.println(a);
        }
    }
}
​

 

public class ArrayDemo2 {
    public static void main(String[] args) {
        int[] numbers = new int[3];
        double[] scores = new double[5];
        String[] names = new String[3];

        System.out.println(numbers[0]);
        System.out.println(scores[0]);
        System.out.println(names[0]);

        // 배열의 길이를 조회한다.
        System.out.println(numbers.length);
        System.out.println(scores.length);
        System.out.println(names.length);

        // 배열에 값을 저장하기
        numbers[0] = 100;
        numbers[1] = 200;
        numbers[2] = 150;

        names[0] = "홍길동";
        names[1] = "이순신";
        names[2] = "강감찬";
        names[3] = "김유신";    // 배열의 인덱스 범위를 초과
    }
}​

 

public class ArrayDemo3 {
    public static void main(String[] args) {

        if (args.length == 2) {
            System.out.println(args[0]);
            System.out.println(args[1]);
        
        } else {
            System.out.println("명령행 인자의 개수가 올바르지 않습니다.");
        }
    }
}
​

 

public class ArrayDemo4 {
    public static void main(String[] args) {

        int[] scores = {70, 20, 50, 44, 28, 70, 80, 100};

        System.out.println("국어 점수 리스트");
        for (int x : scores) {    // enhanced for문
            System.out.println(x);
        }

        int total = 0;
        int average = 0;
        int min = 100;    // 예상되는 가장 큰 값을 담고 시작한다.
        int max = 0;    // 예상되는 가장 작은 값을 담고 시작한다.
        for (int x : scores) {
            total = total + x;
        }
        
        average = total/scores.length;
        
        System.out.println("총점 : " + total);
        System.out.println("평균 : " + average);

        // 최솟값 구하기
        // 배열의 값을 하나씩 꺼내서 min에 저장된 값과 비교해서
        // min 값보다 꺼낸 값이 작다면 min의 값을 지금 꺼낸 값으로 교체한다.
        for (int x : scores) {
            if (x < min) {
                min = x;
            }
        }
        System.out.println("최솟값 : " + min);

        // 최댓값 구하기
        // 배열의 값을 하나씩 꺼내서 max에 저장된 값과 비교해서
        // max값보다 꺼낸 값이 크다면 max의 값을 지금 꺼낸 값으로 교체한다.

        for (int x : scores) {
            if (x > max) {
                max = x;
            }
        }
        System.out.println("최댓값 : " + max);
    }
}​

 

public class ArrayDemo5 {
    public static void main(String[] args) {

        /*
        int[][] arr = new int[2][3];

        
        arr[0][0] = 20;
        arr[0][1] = 50;
        arr[0][2] = 60;

        arr[1][0] = 100;
        arr[1][1] = 90;
        arr[1][2] = 80;
        */

        int[][] arr = {{20, 50, 60}, {100, 90, 80}};

        for (int x=0; x<2; x++) {
            for (int y=0; y<3; y++) {
        System.out.println(arr[x][y]);
            }
        }
    }
}
​

 

import java.util.Scanner;

public class ArrayDemo6 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int studentNumbers = 0;        // 학생 수
        int[] scores = null;        // 점수를 저장하는 배열

        for (;;) {
            System.out.println("---------------------------------------------------------------");
            System.out.println(" 1. 학생 수 | 2. 점수 입력 | 3. 점수 리스트 | 4. 분석 | 0. 종료");
            System.out.println("---------------------------------------------------------------");

            System.out.print("선택> ");
            int selectedNo = scanner.nextInt();

            if (selectedNo == 1 ) {
                System.out.println("학생 수> " );
                studentNumbers = scanner.nextInt();
                scores = new int[studentNumbers];    // 입력된 학생 수만큼의 크기를 가지는 배열을 생성해서 scores에 그 주소를 담는다.
            
            } else if (selectedNo == 2 ) {
                for (int i=0; i<studentNumbers; i++) {
                    System.out.print("[" + i + "]번 째 점수 입력> ");
                    int score = scanner.nextInt();
                    scores[i] = score;
                }
                    
            } else if (selectedNo == 3 ) {
                for (int score : scores) {
                        System.out.print(score + " ");
                }

            } else if (selectedNo == 4 ) {
                int total = 0;
                int highScore = 0;
                for (int score : scores) {
                    total = total + score;
                    if (score > highScore) {
                        highScore = score;
                    }
                }
                    System.out.println("최고 점수: " + highScore);
                    System.out.println("총     점: " + total);
                    System.out.println("평     균: " + total/studentNumbers);
                
            } else if (selectedNo == 0 ) {
                System.out.println("프로그램 종료");
                break;
            }

            System.out.println("\n\n\n");
        }
    }
}
​

 

import java.util.Scanner;

public class ArrayDemo7 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("이름 입력> ");
        String name = scanner.next();        // scanner.next() -> 문자열을 읽어온다.

        System.out.print("나이 입력> ");
        int age = scanner.nextInt();        // scanner.nextInt() -> 숫자를 읽어온다.

        System.out.print("연락처 입력> ");
        String tel = scanner.next();

        System.out.print("몸무게 입력> ");
        double weight = scanner.nextDouble();    // scanner.nextDouble() -> 실수를 읽어온다.

        System.out.println("이름 " + name);
        System.out.println("나이 " + age);
        System.out.println("연락처 " + tel);

    }
}
​

 

import java.util.Scanner;

public class ArrayDemo8 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int productNumbers = 0;
        String[] productNames = null;
        int[] productPrices = null;

        for (;;) {
            System.out.println("---------------------------------------------------------------");
            System.out.println(" 1. 전체 개수 | 2. 구매 상품 정보 입력 | 3. 영수증 출력 0. 종료");
            System.out.println("---------------------------------------------------------------");

            System.out.print("메뉴 선택> ");
            int selectNo = scanner.nextInt();

            if (selectNo == 1) {
                /*
                    전체 상품 개수를 입력받는다.
                    전체 상품 개수만큼 상품 이름을 담는 배열과, 상품 가격을 담는 배열을 생성한다.
                */
                System.out.print("전체 개수> ");                
                productNumbers = scanner.nextInt();
                productNames = new String[productNumbers];
                productPrices = new int[productNumbers];


            } else if (selectNo == 2) {
                /*
                    전체 상품 개수만큼 상품 이름과 상품 가격을 입력받는 작업을 반복한다.
                        상품 이름과 상품 가격을 각각 입력받아서 해당 배열에 순서대로 저장한다.
                */
                for (int x=0 ; x < productNumbers ; x++) {
                    System.out.print("상품의 이름을 입력> ");
                    String productName = scanner.next();
                    productNames[x] = productName;
                    System.out.print("상품의 가격 입력> ");
                    int productPrice = scanner.nextInt();
                    productPrices[x] = productPrice;
                }
                
            } else if (selectNo == 3) {
                /*
                    전체 상품 이름과 상품 가격을 화면에 출력한다(enhanced for문 사용 불가).
                */
                int total = 0;
                for (int z=0; z < productNumbers; z++) {
                System.out.println(productNames[z] + "\t\t\t\t" + productPrices[z]);
                total = total + productPrices[z];
                }
                System.out.println("합계" + total);

            } else if (selectNo == 0) {
                System.out.println("프로그램 종료");
                break;
            }
            System.out.println("\n\n");
        }
    }
}​

 

import java.util.Scanner;

public class ArrayDemo9 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int productKind = 0;
        String[] productNames = null;
        int[] buycounts = null;
        int[] unitPrices = null;

        for (;;) {
            System.out.println("---------------------------------------------------------------");
            System.out.println(" 1. 상품 종류 | 2. 구매 상품 정보 입력 | 3. 영수증 출력 0. 종료");
            System.out.println("---------------------------------------------------------------");

            System.out.print("메뉴 선택> ");
            int selectNo = scanner.nextInt();

            if (selectNo == 1) {
                System.out.print("상품 종류 입력> ");                
                productKind = scanner.nextInt();
                productNames = new String[productKind];
                buycounts = new int[productKind];
                unitPrices = new int[productKind];

            } else if (selectNo == 2) {
                for (int x=0 ; x < productKind ; x++) {
                    System.out.print("상품의 이름을 입력> ");
                    String productName = scanner.next();
                    productNames[x] = productName;

                    System.out.print("구매 수량을 입력> ");
                    int buycount = scanner.nextInt();
                    buycounts[x] = buycount;

                    System.out.print("단가를 입력> ");
                    int unitPrice = scanner.nextInt();
                    unitPrices[x] = unitPrice;
                }

            } else if (selectNo == 3) {
                System.out.println("---------------------------------------------------------------");
                System.out.println("상품명\t\t   구매 수량\t\t단가\t\t가격");
                System.out.println("---------------------------------------------------------------");
                
                int totalBuycounts = 0;
                int total = 0;
                for (int x=0; x<productKind; x++) {
                    System.out.println(productNames[x] + "\t\t\t" + buycounts[x] + "\t\t" + unitPrices[x] + "\t\t" + buycounts[x]*unitPrices[x]);
                    totalBuycounts = totalBuycounts + buycounts[x];
                    total = total + buycounts[x]*unitPrices[x];
                }

                System.out.println("---------------------------------------------------------------");
                System.out.println("합계 : " + "\t\t\t" + totalBuycounts + "\t\t\t\t" + total);

            } else if (selectNo == 0) {
                System.out.print("종료");
                break;
            }
        }
    }
}
​
import java.util.Scanner;

public class BookProgram {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int p = 0;
        int b = 0;
        int t = 0;

        
        System.out.println("책의 가격");
        p = scanner.nextInt();
        System.out.println("구매 수량");
        b = scanner.nextInt();
        
        t = p * b;

        System.out.println("총구매가격 : " + t);
    }
}

 

import java.util.Scanner;

public class BookProgram2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int d = 0;
        int p = 0;
        int b = 0;
        int t = 0;
        boolean s = false;

        System.out.println("등급을 입력하세요");
        d = scanner.nextInt();
        System.out.println("가격을 입력하세요");
        p = scanner.nextInt();
        System.out.println("구매수량을 입력하세요");
        b = scanner.nextInt();

        t = p * b;
        s = d == 1 && t >= 100000;

        System.out.println("총구매가격 : " + t);
        System.out.println("사은품 여부 : " + s);
    }
}

 

public class IfDemo1 {
    public static void main(String[] args) {
        
        int score = 55;

        if(score >= 60) {
            System.out.println("합격하였습니다.");
        } else {
            System.out.println("불합격하였습니다.");
        }
    }
}

 

public class IfDemo2 {
    public static void main(String[] args) {
        
        int score = 40;

        if (score >= 90) {
            System.out.println("A학점 입니다.");
        } else if (score >= 80) {
            System.out.println("B학점 입니다.");
        } else if (score >= 70) {
            System.out.println("C학점 입니다.");
        } else if (score >= 60) {
            System.out.println("D학점 입니다.");
        } else {
            System.out.println("F학점 입니다.");
        }
    }
}

 

public class IfDemo3 {
    public static void main(String[] args) {
        
        int score = 55;
        
        // 60점 이상 합격(합격자중에서 95점 이상 입학금 면제, 그외 입학금 10만원)
        if (score >= 60) {
            System.out.println("합격입니다.");
            if (score >= 95) {
                System.out.println("입학금 면제대상입니다.");
            } else {
                System.out.println("입학금 10만원을 납부하세요.");
            }
        } else {
            System.out.println("불합격입니다.");
        }
    }
}
​

 

import java.util.Scanner;

public class IfDemo4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 국어, 영어, 수학점수를 입력받아서 
        //평균이 70점 이상이면 합격, 그 외는 불합격으로 표시하는 프로그램
        int k = 0;
        int e = 0;
        int m = 0;
        int a = 0;

        System.out.println("국어 점수 입력");
        k = scanner.nextInt();
        System.out.println("영어 점수 입력");
        e = scanner.nextInt();
        System.out.println("수학 점수 입력");
        m = scanner.nextInt();

        a = (k + e + m) / 3;

        String result = "";
        if (a >= 60) {
            result = "합격";
        } else {
            result = "불합격";
        }

        System.out.println("합격여부 : " + result);

        /*if(a >= 70) {
            System.out.println("합격");
        } else {
            System.out.println("불합격");
        }*/
    }
}
​

 

import java.util.Scanner;

public class IfDemo5 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 상품가격, 상품수량을 입력받아서 총구매가격을 표시하고 
        // 총구매가격이 50만원이상이면 5만원 상품권
        // 총구매가격이 30만원이상이면 1만원 상품권
        // 그 외는 1시간 무료주차권을 제공하는 프로그램
        int p = 0;
        int d = 0;
        int t = 0;

        System.out.println("상품가격");
        p = scanner.nextInt();
        System.out.println("상품수량");
        d = scanner.nextInt();

        t = p * d;
        System.out.println("총구매가격 : " + t);

        String g = "";
        if(t >= 500000) {
            g = "5";
        } else if(t >= 300000) {
            g = "1"
        } else {
            g = "무";
        }
        System.out.println(g + "를 지급");
        /*if(t >= 500000) {
            System.out.println("5");
        } else if(t >= 300000) {
            System.out.println("3");
        } else {
            System.out.println("무");
        }*/
    }
}​

 

import java.util.Scanner;

public class IfDemo6 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 상품가격, 구매수량을 입력받아서 총구매가격을 계산하고
        // 50만원 이상 구매시 총구매금액의 5% 할인 totalPrice*5/100
        // 30만원 이상 구매시 총구매금액의 2% 할인
        // 그 외 할인 없음

        //상품가격, 구매수량, 총구매가격, 할인받은 금액, 실제지불금액을 표시하기

        int a = 0;
        int b = 0;
        int c = 0;
        int d = 0;
        int t = 0;

        System.out.println("상품가격");
        a = scanner.nextInt();
        System.out.println("구매수량");
        b = scanner.nextInt();

        t = a*b;
        System.out.println("총구매가격 : " + t);

        if(t >= 500000) {
            c = t*5/100;
        } else if (t >= 300000) {
            c = t*2/100;
        }

        System.out.println("할인받은금액 : " + c);

        d = t - c;
        System.out.println("실제지불금액 : " + d);
    }
}​

 

import java.util.Scanner;

public class IfDemo7 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 상품가격, 구매수량, 현재 포인트를 입력받는다.
        // 50만원 이상 구매시 총구매금액의 5% 할인 totalPrice*5/100
        // 30만원 이상 구매시 총구매금액의 2% 할인
        // 그 외 할인 없음

        // 현재 포인트가 1만점 이상일 때는 실제지불금액의 0.3%를 포인트로 적립
        // 현재 포인트가 5천점 이상일 때는 실제지불금액의 0.2%를 포인트로 적립
        // 그 외 0.1%를 포인트로 적립
        
        // 상품가격, 구매수량, 총구매가격, 할인받은 금액, 실제지불금액을 표시
        // 적립전 포인트, 포인트적립량, 적립후 포인트

        int price = 0;
        int amount = 0;
        int totalPrice = 0;
        int discountPrice = 0;
        int payPrice = 0;

        int currentPoint = 0;
        int point = 0;
        int savedPoint = 0;
        
        System.out.println("상품가격");
        price = scanner.nextInt();
        System.out.println("구매수량");
        amount = scanner.nextInt();
        System.out.println("현재 포인트");
        currentPoint = scanner.nextInt();

        totalPrice = price*amount;

        if(totalPrice >= 500000) {
            discountPrice = totalPrice*5/100;
        } else if (totalPrice >= 300000) {
            discountPrice = totalPrice*2/100;
        }

        payPrice = totalPrice - discountPrice;

        if(currentPoint >= 10000) {
            savedPoint = payPrice*3/1000;
        } else if(currentPoint >= 5000)
            savedPoint = payPrice*2/1000;
        } else {
            savedPoint = payPrice*1/1000;
        }

        point = currentPoint + savedPoint;

        System.out.println("상품가격 : " + price);
        System.out.println("구매수량 : " + amount);
        System.out.println("총구매가격 : " + totalPrice);
        System.out.println("할인받은 금액 : " + discountPrice);
        System.out.println("실제지불금액 : " + payPrice);
        System.out.println("적립전 포인트 : " + currentPoint);
        System.out.println("포인트적립량 : " + point);
        System.out.println("적립후 포인트 : " + savedPoint);
    }
}
​

 

public class SwitchDemo1 {
    public static void main(String[] args) {
        
        String grade = "골드";

        switch (grade) {
            case "골드" : 
                System.out.println("5%가 적립됩니다.");
                break;
            case "실버" : 
                System.out.println("3%가 적립됩니다.");
                break;
            case "브론즈" : 
                System.out.println("1%가 적립됩니다.");
                break;
            default : 
                System.out.println("적립되지 않습니다.");
        }
    }
}
​

 

public class ForDemo1 {
    public static void main(String[] args) {
        
        for (int i=1; i<=5; i++) {
            System.out.println(i + "번째 실행");
        }
    }
}​

 

public class ForDemo2 {
    public static void main(String[] args) {
        
        int total = 0;

        for (int i=1; i<=100; i+=2) {
            System.out.println(i);
            total = total + i;
        }

        System.out.println("합계 : " + total);
    }
}​

 

import java.util.Scanner;

public class ForDemo3 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        /*
        //1부터 입력받은 숫자까지의 합계를 계산하는 프로그램

        int total = 0;
        int num = 0;

        System.out.println("숫자 입력");
        num = scanner.nextInt();

        for (int i=1; i<=num; i++) {
            total += i;
        }

        System.out.println("합계 : " + total);
        */

        // 숫자 두개를 입력받아서 첫번째 숫자부터 두번째 숫자 사이의 합계를 구하는 프로그램

        int begin = 0;
        int end = 0;
        int total = 0;

        System.out.println("시작 숫자 입력");
        begin = scanner.nextInt();
        System.out.println("끝 숫자 입력");
        end = scanner.nextInt();

        if(begin < end) { // 긍정적인 조건을 if, 부정적인 조건은 else
            for (int i=begin; i<=end; i++) {
                total += i;
            }
        
            System.out.println("합계 : " + total);
        } else {
            System.out.println("값이 올바르지 않습니다");
        }

        
    }
}
​

 

public class ForDemo5 {
    public static void main(String[] args) {
        
        for (int i=1; i<=10; i++) {
            System.out.println(i);
            
            if (i == 6) {
                break;
            }
        }
    }
}​

 

public class ForDemo6 {
    public static void main(String[] args) {
        
        for (int i=1; i<=10; i++) {
            if (i == 6) {
                continue;
            }
            System.out.println(i);
        }
    }
}​

 

import java.util.Scanner;

public class ForDemo7 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int giftCard = 0;
        int totalPrice = 0;

        // 여러 개의 상품가격을 입력받아서, 구매금액이 상품권가격을 초과하면
        // 가격입력을 중지하고 현재 총 구매금액을 출력

        System.out.println("상품권 가격 스캔");
        giftCard = scanner.nextInt();

        for (;;) { 
            if(totalPrice <= giftCard) { 
                int price = 0;
                System.out.println("상품을 스캔하세요");
                price = scanner.nextInt();
                totalPrice = totalPrice + price;
            } else {
                break;
            } 

        }
        System.out.println("구매 금액 : " + totalPrice);
    }
}
​

 

import java.util.Scanner;

public class ForDemo8 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
            
        int dan = 0;

        System.out.println("출력할 단을 입력하세요");
        dan = scanner.nextInt();

        // 구구단 출력
        for (int i=1; i<=9; i++) {
            System.out.println(dan + " * " + i + " = " + (dan*i));
        }
    }
}​

 

public class ForDemo9 {
    public static void main(String[] args) {
        for (int x=1; x<=2; x++) {
            //System.out.println("바깥쪽 for문의 수행문");
            System.out.println("["+x+"]");
            for (int y=1; y<=3; y++)
                //System.out.println("안쪽 for문의 수행문");
                System.out.println("{"+x+"}{"+y+"}");
            }
        }
    }
}​

 

public class ForDemo10 {
    public static void main(String[] args) {
        
        for (int i=1; i<=6; i++) {
            int number = (int)(Math.random()*45 + 1); // Math.random() - 0보다 크고 1보다 작은 임의의 실수를 만듦
            // 0 < Math.random()*45 < 1 -- 1 < Math.random()*45 + 1 < 46
            System.out.println(number);
        }
    }
}
​

 

public class ForDemo11 {
    public static void main(String[] args) {

        for (int x=1; x<=9; x++) {
            for (int i=2; i<=9; i++) {
                System.out.print(i + " * " + x + " = " + (i*x) + "\t\t\t");
                if (x*i < 10) {
                    System.out.print(" ");
                }
            }
            System.out.println();
        }
    }
}​

 

import java.util.Scanner;

public class ForDemo12 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // 임의의 숫자 만들기
        int number = (int)(Math.random()*20 + 1);

        // 숫자를 입력받아서 임의의 숫자와 일치하는지 알아내기
        for (;;) {
            // 사용자로부터 숫자를 입력받는다.
            // 입력받은 숫자가 number에 들어있는 값보다 크다면 "작다"를 출력하고, 아니면 "크다"를 출력한다
            // 입력받은 숫자가 number와 일치하면 반복문을 탈출한다.
            
            System.out.println("숫자를 맞춰보세요");
            
            int inputNumber = scanner.nextInt();

            /*if (number > inputNumber) {
                System.out.println("크다");
            } else if (number < inputNumber) {
                System.out.println("작다");
            }

            if (number == inputNumber) {
                System.out.println("정답");
                break;
            }*/
            if (number > inputNumber) {
                System.out.println("크다");
            } else if (number < inputNumber) {
                System.out.println("작다");
            } else {
                System.out.println("정답");
                break;
            }
        }
        System.out.println("임의의 숫자 : " + number);
    }
}
​

 

public class ForDemo13 {
    public static void main(String[] args) {
        
        for (int x=1; x<=5; x++) {
            for (int y=1; y<=x; y++) {
                System.out.print(x);
            }
            System.out.println();
        }
    }
}​

 

public class ForDemo14 {
    public static void main(String[] args) {
        
        int c = 0;
        for (int x=1; x<=4; x++) {
            for (int y=1; y<=x; y++) {
                c++;
                System.out.print(c);
            }
            System.out.println();
        }
    }
}​

 

public class Sample {
    public static void main(String[] args) {
        System.out.println("자바의 세상에 온 것을 환영합니다.");
    }
}
/*
---------- 실행 ----------
자바의 세상에 온 것을 환영합니다.
출력 완료 (0초 경과) - 정상 종료
*/
 

 

public class Sample2 {
    public static void main(String[] args) {
        System.out.println("홍길동");
        System.out.println(100 + 100);
        System.out.println(1042 * 5);
    }
}
/*
---------- 실행 ----------
홍길동
200
5210

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class VarDemo1 {
    public static void main(String[] args) {
        
        int age = 30;
        double height = 187.6;
        String username = "홍길동";
        boolean married = false;

        System.out.println(age);
        System.out.println(height);
        System.out.println(username);
        System.out.println(married);
    }
}
/*
---------- 실행 ----------
30
187.6
홍길동
false

출력 완료 (0초 경과) - 정상 종료
*/
​

 

public class VarDemo2 {
    public static void main(String[] args) {
        
        String name = "이이이";
        int age = 20;
        String num = "010-0000-0000";
        String e = "aaaaa@bbbbbbb";
        String add = "경기도 안성시";
        double h = 180;
        double w = 100;
        String b = "A";

        System.out.println(name);
        System.out.println(age);
        System.out.println(num);
        System.out.println(e);
        System.out.println(add);
        System.out.println(h);
        System.out.println(w);
        System.out.println(b);
    }
}
/*
---------- 실행 ----------
이이이
20
010-0000-0000
aaaaa@bbbbbbb
경기도 안성시
180
100
A

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class VarDemo3 {
    public static void main(String[] args) {
        
        // 변수의 선언(변수의 정의, 변수의 생성)
        int a;
        // 변수의 초기화
        a = 200;

        // 변수에 저장된 값 사용
        System.out.println(a);

    }
}
/*
---------- 실행 ----------
200

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class VarDemo4 {
    public static void main(String[] args) {
        
        // 변수의 값은 사용하는 싯점에 따라서 결과값이 다를 수 있다.

        // 변수를 생성하고 값을 대입
        int num1 = 100;
        int num2 = 200;
        System.out.println(num1 + num2);

        // 기존 변수에 새로운 값을 대입(새로운 값으로 변경)
        num1 = 600;
        num2 = 300;
        System.out.println(num1 + num2);
    }
}
/*
---------- 실행 ----------
300
900

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class TypeDemo1 {
    public static void main(String[] args) {
        // 정수타입 : byte, short, int, long
        
        // byte b = 1000; 해당 타입이 가질 수 있는 값의 점위를 초과하는 값은 저장할 수 없다.

        /* long타입의 변수에 값을 담을 때는 정수값의 끝에 L을 붙여서 long타입의 범위내에서 그 값을 다루도록 한다.
        * 자바는 모든 정수 리터럴(정수값)을 int의 범위에서 다루려고 한다. */
        long num1 = 10000000000L;
        System.out.println(num1);

        int num2 = 1000000;
        int num3 = 1_000_000; // 정수를 적을 때 자릿수를 표현하는 _를 같이 적을 수 있다.
        System.out.println(num2);
        System.out.println(num3);
    }
}
/*
---------- 실행 ----------
10000000000
1000000
1000000

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class TypeDemo2 {
    public static void main(String[] args) {
        // 문자타입 : char

        char c1 = 'A';
        // char c1 = "A"; // 에러 "A"는 문자열이다.
        
        // 유니코드 0041번에 해당하는 글자가 c2에 저장된다.
        char c2 = '\u0041';
        // 아스키코드 65번에 해당하는 글자가 c3에 저장된다.
        char c3 = 65; 

        System.out.println(c1);
        System.out.println(c2);
        System.out.println(c3);


        System.out.println("123\t123\n\n123");
        System.out.println("정보처리 시험에 \"합격\"하였습니다.");
    }
}
/*
---------- 실행 ----------
A
A
A
123    123

123
정보처리 시험에 "합격"하였습니다.

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class TypeDemo3 {
    public static void main(String[] args) {
        // 실수 타입 : float, double
        
        double num1 = 3.14;
        // 모든 실수는 double 범위에서 판단된다.
        // 실수 끝에 f를 붙이면 float 범위에서 판단하게 한다.
        float num2 = 3.14f;

        System.out.println(num1);
        System.out.println(num2);
    }
}
​

 

public class TypeDemo4 {
    public static void main(String[] args) {
        
        double num1 = 0.1;
        double num2 = 0.2;

        System.out.println(num1 + num2);
    }
}

 

// 클래스명은 대문자로 시작
// 자바의 모든 프로그램은 클래스 내부에 정의
 public class VarDemo5 {
    public static void main(String[] args) {
        
        String title = "이것이 자바다";
        String publisher = "한빛미디어";
        int price = 30000;
        String pubdate = "2015년 1월 5일";
        String writer = "신용권";
        double discountRate = 0.05;
        boolean soldout = false;
        boolean best = true;
        boolean freeShipping = true;

        System.out.println(title);
        System.out.println(publisher);
        System.out.println(price);
        System.out.println(pubdate);
        System.out.println(writer);
        System.out.println(discountRate);
        System.out.println(soldout);
        System.out.println(best);
        System.out.println(freeShipping);
    } /* - 메인 메소드 : JVM이 항상 처음으로 찾는 메소드
                         진입점이 되는 메소드
                         프로그램이 반드시 가져야되는 메소드*/
      // 메소드는 수행문을 가질 수 있다
} // - 바디, 수행문을 가질 수 없다

/*
---------- 실행 ----------
이것이 자바다
한빛미디어
30000
2015년 1월 5일
신용권
0.05
false
true
true

출력 완료 (0초 경과) - 정상 종료
*/​

 

public class CastingDemo1 {
    public static void main(String[] args) {
        double num1 = 10;
        System.out.println(num1);
        
        // 자바는 연산에 참여한 타입과 같은 타입의 결과가 나옴
        // 타입이 다를 경우 더 큰 타입으로 변환
        int num2 = 3; // 정수
        int num3 = 10; // 정수
        System.out.println(num2 / num3); // 정수/정수 ---> 정수

        double num4 = 3.0; // 실수
        double num5 = 10.0; // 실수
        System.out.println(num4 / num5); // 실수/실수 ---> 실수

        System.out.println(num2 / num5); // 정수/실수 -> 실수/실수 --->실수
    }
}
/*
자동형변환
1. 작은 타입의 값을 큰 타입의 그릇에 담을 때
2. 덜 정밀한 타입의 값을 정밀한 타입의 그릇에 담을 때
3. 연산에 참여한 값의 타입과 연산의 결과가 같은 타입이 되게 할 때
4. 연산에 참여한 값의 타입이 서로 다른 경우 더 큰 타입의 값으로 변경될 때
*/​

 

public class CastingDemo2 {
    public static void main(String[] args) {
        
        // int num1 = 3.14; 데이터가 손실되는 타입 변환은 에러
        int num1 = (int) 3.14;
        System.out.println(num1);

        int num2 = 10;
        System.out.println(num2);
        System.out.println( (double)num2 );
    }
}

 

public class CastingDemo3 {
    public static void main(String[] args) {
        int kor = 50;
        int math = 60;
        int eng = 80;

        // 국어점수, 수학점수, 영어점수를  전부 합한 결과를 totalScore에 대입
        int totalScore = kor + math + eng;
        System.out.println(totalScore);

        // 현재 totalScore에 저장된 값 --> 190
        // (double) 190 / 3 -->190.0 / 3 -> (타입 변환) 190.0 / 3.0 -->63.3333..
        // avg 그릇에 대입된 값은 63.3333.. 이다.
        double avg = (double)totalScore / 3;
        // double avg = totalScore / 3.0;
        System.out.println(avg);
    }
}

 

public class OpDemo1 {
    public static void main(String[] args) {
        // 산술연산자 : + - * / %
        int num1 = 7;
        int num2 = 3;

        System.out.println(num1 / num2); // 몫을 계산한다
        System.out.println(num1 % num2); // 나머지를 계산한다
        // 나머지 연산자(modular) : 나누는 수보다 큰 수는 나올 수 없음
    }
}

 

public class OpDemo2 {
    public static void main(String[] args) {
        String str1 = "서울특별시";
        String str2 = " 종로구 봉익동";
        String str3 = str1 + str2;
        System.out.println(str3);
        
        String str4 = 3 + 6 + "abc";
        String str5 = "abc" + 3 + 6;
        System.out.println(str4);
        System.out.println(str5);
    }
}

 

public class OpDemo3 {
    public static void main(String[] args) {
        int kor = 65;
        int math = 79;
        int eng = 87;

        System.out.println("국어점수 " + kor);
        System.out.println("수학점수 " + math);
        System.out.println("영어점수 " + eng);
        System.out.println("종합점수 " + (kor + math + eng));
    }
}

 

public class OpDemo4 {
    public static void main(String[] args) {
        // 대입연산자 : = += -= *= /= %=
        
        int a = 10;
        a = a + 1;
        System.out.println(a);
        
        a = a + 1; // a의 값과 1을 더한 다음 그 값을 다시 a에 저장
        System.out.println(a);

        a += 1; // a의 값을 1씩 증가
        System.out.println(a);

        a -= 1; // a의 값을 1씩 감소
        System.out.println(a);

        a += 2;
        System.out.println(a);

        a *= 2;
        System.out.println(a);
    }
}

 

public class OpDemo5 {
    public static void main(String[] args) {
        int a = 10;

        a++; // a의 값 1 증가, 다른 연산과 같이 사용하게되면 연산참여 후 증가
        System.out.println(a);

        ++a; // a의 값 1 증가, 다른 연산과 같이 사용하게되면 증가 후 연산참여
        System.out.println(a);

        int b = 100;

        b--; // b의 값 1 감소
        System.out.println(b);

        --b; // b의 값 1 감소
        System.out.println(b);
    }
}

 

public class OpDemo6 {
    public static void main(String[] args) {
        int a = 10;
        int x = ++a; // a가 1 증가됨, 11이 x에 대입도미
        System.out.println("a -> " + a);
        System.out.println("x -> " + a);

        int b = 10;
        int y = b++; // b의 값이 대입됨, b가 1 증가됨
        System.out.println("b -> " + b);
        System.out.println("y -> " + y);
    }
}

 

public class OpDemo7 {
    public static void main(String[] args) {
        // 비교연산자 : == != > < >= <=
        // 비교연산자의 연산 결과는 항상 true 혹은 false 값이다

        int a = 5;
        int b = 4;

        boolean result1 = a == b;
        System.out.println(result1);

        boolean result2 = a != b;
        System.out.println(result2);

        System.out.println(a > b);
        System.out.println(a >= b);
        System.out.println(a < b);
        System.out.println(a <= b);
    }
}

 

public class OpDemo8 {
    public static void main(String[] args) {
        // 논리연산자 : && || !
        // 논리연산자의 연산 대상은 true 혹은 false 값을 결과로 내놓은 식이다.
        // 논리연산자의 연산 결과는 true 혹은 false 값이다.

        int year = 2017;
        int distance = 60000;
        
        // 구매기간이 3년이 경과된 경우 혹은 주행거리가 5만 km 이상인 경우 유상처리
        boolean result = (2019 - year) > 3 || distance >= 50000;
        System.out.println("유상수리 여부 -> " + result);
    }
}

 

import java.util.Scanner;

public class OpDemo9 {
    public static void main(String[] args) {
        // 키보드 입력을 읽어오는 객체 만들기
        Scanner scanner = new Scanner(System.in);

        System.out.println("### 합격여부 판단 프로그램 ###");

        int kor = 0;
        int math = 0;
        int eng = 0;
        int total = 0;
        int avg = 0;
        boolean pass = false; // 합격여부를 담는 그릇

        System.out.println("국어점수를 입력하세요");
        kor = scanner.nextInt();
        System.out.println("수학점수를 입력하세요");
        math = scanner.nextInt();
        System.out.println("영어점수를 입력하세요");
        eng = scanner.nextInt();

        total = kor + math + eng;
        avg = total / 3;
        pass = avg >= 60;

        System.out.println("국어점수 : " + kor);
        System.out.println("수학점수 : " + math);
        System.out.println("영어점수 : " + eng);
        System.out.println("종합점수 : " + total);
        System.out.println("평균점수 : " + avg);
        System.out.println("합격여부 : " + pass);
    }
}

 

import java.util.Scanner;

public class OpDemo10 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.println("### 수리비 계산 프로그램 ###");

        int year = 0; // 구매년도
        int distance = 0; //주행거리
        boolean pay = false; //유상수리 여부
        
        System.out.println("구매년도를 입력하세요");
        year = scanner.nextInt();
        System.out.println("주행거리를 입력하세요");
        distance = scanner.nextInt();
        
        // 구매기간이 3년을 넘거나 주행거리가 50000km를 넘는 경우 유상수리로 판단
        pay = (2019 - year) > 3 || distance > 50000;

        System.out.println("유상수리 여부 " + pay);
    }
}

 

import java.util.Scanner;

public class OpDemo11 {
    public static void main(String[] args) {
        // 책가격, 구매수량을 입력받아서 총구매가격을 표시하기
        Scanner scanner = new Scanner(System.in);

        int price = 0;
        int amount = 0;
        int totalPrice = 0;

        System.out.println("책 가격을 입력하세요");
        price = scanner.nextInt();
        System.out.println("구매수량을 입력하세요");
        amount = scanner.nextInt();

        totalPrice = price * amount;
        
        System.out.println("총구매가격 : " + totalPrice);
    }
}

 

public class OpDemo12 {
    public static void main(String[] args) {
        /*
        삼항연산자 -> 조건식 ? 값1      : 값2
                      조건식 ? 연산식1 : 연산식2
        값1과 값2의 타입은 동일해야 한다.
        연산식1과 연산식2의 계산결과도 타입이 동일해야 한다.
        조건식의 계산결과가 true이면 값1, false이면 값2가 삼항연산자의 연산결과가 된다.
        */

        int score = 55;
        String result = (score > 60 ? "합격" : "불합격");

        System.out.println("최종결과 " + result);

        int totalPrice = 100000;
        int grade = 1;

        double point = (grade == 1 ? totalPrice * 0.03 : totalPrice * 0.01);

        System.out.println("포인트 " + point);
    }
}

'자바 > basic' 카테고리의 다른 글

RefDemo2, ArrayDemo9.java  (0) 2019.06.07
BookProgram2, IfDemo7, SwitchDemo1, ForDemo14(4 없음).java  (0) 2019.06.07

+ Recent posts