• 과일의 가격, 할인율, 할인율에 따른 과일가격 변동 출력 (Good, GoodMain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day05_object;
public class Good {
     String num;
     String name;
     String company;
     int price;
     double discountRate;
     
     public Good(String num, String name, String company, int price) {
          this.num=num;
          this.name=name;
          this.company=company;
          this.price=price;
     }
     
     public int getSellingPrice() {
          return price-(int)(price*discountRate);
     }
     
     public void updateDiscountRate(double rate) {
          discountRate=rate;
     }
     
     public double discountRate() {
          return discountRate;
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
ackage day05_object;
public class GoodMain {
     public static void main(String[] args) {
          Good g1=new Good("001","레몬","레몬사",1000);
          System.out.println(g1.name+":"+g1.getSellingPrice());
          
          Good g2=new Good("002","사과","애플사",1500);
          System.out.println(g2.name+":"+g2.getSellingPrice());
     
          g2.updateDiscountRate(0.2);
          
          System.out.println("사과:"+g2.getSellingPrice());
          System.out.println(g2.name+"할인율: "+g2.discountRate());
     }
}

 


  • 배열에 책제목과 저자 입력하고 출력하기 (BookBean, BookMain)
  • public은 누구나 접근.
  • default는 접근제어자 생략. 같은 패키지 안에서는 접근가능.
  • private은 자신만 접근.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day06_objectArray;
public class BookBean {
     private String title;
     private String writer;
     
     public BookBean(String title, String writer) {
          this.title=title;
          this.writer=writer;
     }
     //getter. title과 writer가 private이기 때문에
     //BookMain에서 접근하지 못함.
     //따라서 public으로 메소드를 만들어서 값을 돌려주기.
     public String getTitle() {
          return title;
     }
     
     public String getWriter() {
          return writer;
     }
     
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package day06_objectArray;
 
import java.util.Scanner;
 
public class BookMain {
    static Scanner sc =new Scanner(System.in);
    BookBean[]arr=new BookBean[50];
    int cnt; //멤버변수의 초기값은 0이라서 굳이 0 안줘도 됨.
    
    public void showMenu() {
        System.out.println("선택하세요");
        System.out.println("1.데이터입력");
        System.out.println("2.전체보기");
        System.out.println("3.종료");
        System.out.println("선택>>");
    }
    //데이터 입력
    public void bookInsert() {
        System.out.println("데이터 입력하세요...");
        System.out.print("책제목: ");
        String title=sc.nextLine(); //한줄 입력받는 것. 한줄은 엔터 입력 전까지 인식.
        System.out.print("책저자: ");
        String writer=sc.nextLine();
        arr[cnt++= new BookBean(title, writer); //입력받으면 배열에 저장하기.
    }
    
    public void bookList() {
        System.out.println("제목\t작가");
        /*
        for(int i=0;i<cnt;i++) {
            System.out.print(arr[i].title+"\t");
            System.out.print(arr[i].writer+"\n");
        }
        */
        
        for(BookBean book : arr) { //향상된 for문. for-each
            if(book==nullbreak;
            System.out.print(book.getTitle()+"\t");
            System.out.print(book.getWriter()+"\n");
        }
        
    }
    
    public static void main(String[] args) {
        BookMain bm=new BookMain();
        while(true) {
            bm.showMenu(); //메뉴
            int choice=sc.nextInt();
            BookMain.sc.nextLine(); //그 전의 엔터를 버림
            switch(choice) {
            case 1 : bm.bookInsert(); break;
            case 2 : bm.bookList(); break;
            case 3 : System.out.println("종료");
                     System.exit(0);
            default : System.out.println("입력오류");
            }
        }
    }
}

 


  • 배열에 선수 데이터입력하고 선수 이름과 나이 출력하기 (Player, PlayerManager, PlayerMain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package day06_objectArray;
 
public class Player {
    private String name, address;
    private int age;
    private double height, weight;
 
    public Player(String name, String address, int age, double height, double weight) {
        this.name=name;
        this.address=address;
        this.age=age;
        this.height=height;
        this.weight=weight;
    }
 
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void getInfo() {
        System.out.println("이름: " +name);
        System.out.println("주소: " +address);
        System.out.println("나이: " +age);
        System.out.println("키: " +height);
        System.out.println("몸무게: " +weight);
    }
 
}
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package day06_objectArray;
 
public class PlayerManager {
    private final int MAX_INT=50;
    Player[]arr=new Player[MAX_INT];
    private int cnt;
    
    void insertPlayer() {
        System.out.println("선수 정보 등록...");
        System.out.print("이름: ");
        String name=PlayerMain.sc.nextLine();
        System.out.print("주소: ");
        String address=PlayerMain.sc.nextLine();
        System.out.print("나이: ");
        int age=PlayerMain.sc.nextInt();
        System.out.print("키: ");
        double height=PlayerMain.sc.nextDouble();
        System.out.print("몸무게: ");
        double weight=PlayerMain.sc.nextDouble();
        arr[cnt++]=new Player(name, address, age, height, weight);
    }
    
    public void viewPlayer() {
        System.out.println("선수이름\t나이");
        for(Player player : arr) {
            if(player==nullbreak;
            System.out.print(player.getName()+"\t");
            System.out.print(player.getAge()+"\n");
        }
    }
    
    public void searchPlayer() {
        System.out.println("찾을 선수 이름>>");
        String searchName=PlayerMain.sc.next();
        Player p = search(searchName);
        if(p==null) {
            System.out.println("찾는 선수 없음");
            return;
        }
        p.getInfo();
    }
    
    public Player search(String searchName) { //리턴형이 객체일 수도 있다.
        for(int i=0;i<cnt;i++) {
            if(searchName.equals(arr[i].getName())) {
                return arr[i]; //객체를 리턴시켜줌.
            }
        }
        return null;
    }
        
    /*
    public void searchPlayer() {
        System.out.println("찾을 선수 이름>>");
        //이름이 같으면 찾는 선수
        //찾는 선수의 모든 정보를 출력
        //없으면 찾는 선수가 없습니다. 라고 출력
        
        String search=PlayerMain.sc.next();
        Player p=null;
 
        for(int i=0;i<cnt;i++) {
            if(search.equals(arr[i].getName())) {
                p=arr[i];
                break;
            }
        }
        if(p!=null) {
            //이름, 나이, 주소, 키, 몸무게
            p.getInfo();
        }else{
            System.out.println("찾는 선수가 없습니다.");
        }
        */
}
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package day06_objectArray;
 
import java.util.Scanner;
 
public class PlayerMain {
    static Scanner sc=new Scanner(System.in);
 
    public static void showMenu() {
        System.out.println("선택하세요");
        System.out.println("1.선수 데이터입력");
        System.out.println("2.전체보기");
        System.out.println("3.선수찾기");
        System.out.println("4.종료");
        System.out.println("선택>>");
    }
    
    public static void main(String[] args) {
        PlayerManager pm=new PlayerManager();
        while(true){
            PlayerMain.showMenu();
            int choice=PlayerMain.sc.nextInt();
            PlayerMain.sc.nextLine();
            switch(choice) {
            case 1 : pm.insertPlayer(); break
            //PlayerManager에다 pm을 만들었으니
            //PlayerManager에서 insertPlayer, viewPlayer메소드 만들어줌.
            case 2 : pm.viewPlayer(); break//이름, 나이 출력
            case 3 : pm.searchPlayer(); break;
            case 4 : System.out.println("종료");
                     System.exit(0);
            default : System.out.println("입력오류");
            }
        }
    }
}
 

 


 

  • Drink, DrinkMain 클래스 구분하여 차종류와 가격 출력하기 (Drink, DrinkMain)
1
2
3
4
5
6
7
8
9
10
11
12
13
package day05_object;
public class DrinkMain {
     
     public static void main(String[] args) {
          Drink coffee=new Drink("커피"5003);
          coffee.getData(); //커피 500 3 1500
          
          Drink tea=new Drink("녹차"8005);
          tea.getData(); //녹차 800 5 4000
          //판매금액
          System.out.println("판매금액: "+(coffee.getTotal()+tea.getTotal()));
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day05_object;
public class Drink {
     String menu;
     int price;
     int quantity;
     
     public Drink(String menu, int price, int quantity) {
          this.menu=menu;
          this.price=price;
          this.quantity=quantity;
     }
     
     public void getData() {
          System.out.print(menu+"\t");
          System.out.print(price+"\t");
          System.out.print(quantity+"\t");
          //System.out.print(price*quantity+"\n");
          System.out.println(getTotal()+"\n"); //판매금액
     }
}

 

 

+배열안에 객체 만들기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day05_object;
public class DrinkTeaMain {
     
     
     public static void main(String[] args) {
          Drink[]arr=new Drink[100];
          //커피         500 3 1500
          //녹차         800 5 4000
          //카페라떼     1500 5 7500
     
          arr[0]=new Drink("커피"5003); //배열안에 객체 만들기
          arr[1]=new Drink("녹차"8005);
          arr[2]=new Drink("카페라떼"15005);
          
          //총판매액 출력
          
          int sum=0;
          
          for(int i=0;i<arr.length;i++) {
              if(arr[i]==nullbreak;
              arr[i].getData();
              sum+=arr[i].getTotal();
          }System.out.println("총판매액: "+sum);
          
          
     }
}
cs

 


  • 성적입력 메뉴를 메소드로 만들고 이차원배열로 성적 입력, 출력, 총점으로 석차구하기 (TwoArrayScore)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package day05_object;
import java.util.Scanner;
public class TwoArrayScore {
     static Scanner sc=new Scanner(System.in);
     int[][] arr=new int[50][7]; //50개의 행과 7개의 열(학번, 국, 영, 수, 총점, 평균, 석차)을 가진 이차원 배열 선언
     //입력되는 성적들이 다른 값들로 대체되어 지워지지 않게 배열에다가 저장해둠.
     int row=0;
     
     public void showMenu() {
          System.out.println("선택하세요");
          System.out.println("1.데이터입력");
          System.out.println("2.전체보기/종료");
          System.out.println("선택>>");
     }
     
     public void inputData() { //성적입력
          System.out.println("성적입력 시작>>");
          System.out.print("학번>>");
          int yearNum=sc.nextInt();
          System.out.print("국어>>");
          int kor=sc.nextInt();
          System.out.print("영어>>");
          int eng=sc.nextInt();
          System.out.print("수학>>");
          int math=sc.nextInt();
          arr[row][0]=yearNum;         //학번
          arr[row][1]=kor;             //국어성적
          arr[row][2]=eng;             //영어성적
          arr[row][3]=math;       //수학성적
          arr[row][4]=kor+eng+math; //총점
          arr[row][5]=arr[0][4]/3;  //평균
          arr[row][6]=1;               //석차
          row++;
     
     }
     
     public void viewData() { //전체보기
          System.out.println("------성적 보기------");
          System.out.print("학번\t국어\t수학\t영어\t총점\t평균\t순위");
          System.out.println();
          for(int i=0;i<row;i++) {
              for(int j=0;j<arr[i].length;j++) { //arr각 방에 들어있는 길이. 과목이 추가될 수도 있으니..
                   System.out.print(arr[i][j]+"\t");
              }System.out.println();
          }
     }
     
     public static void main(String[] args) {
          TwoArrayScore manager=new TwoArrayScore();
          while(true) {
              manager.showMenu(); //메뉴보여주기
              int num=sc.nextInt(); //메뉴 선택
              switch(num) {
              case 1 : manager.inputData(); break//성적입력
              case 2 : manager.viewData(); System.exit(0); //전체보기/ 종료
              default : System.out.println("입력오류");
              }
              
          }
     }
}

+석차를 어떻게 구할것인가??

1
2
3
4
5
6
7
8
9
10
11
public void rankMethod() { //석차 구하는 메소드
          for(int i=0;i<row-1;i++) {
              for(int j=i+1;j<row;j++) {
                   if(arr[i][4]>arr[j][4]) {
                        arr[j][6]++;
                   }else {
                        arr[i][6]++;
                   }
              }
          }
     }    

  • 배열을 이용하여 반지름이 1,2,3,4,5인 5개의 CircleBean객체를 만들고 각 넓이와 총 면적을 구하시오 (CircleBean, CircleBeanMain)
1
2
3
4
5
6
7
8
9
10
11
12
package day05_object;
public class CircleBean {
     int r;
     final double PI=3.14//final이 앞에 붙으면 상수
     
     public CircleBean(int r) {
          this.r=r;
     }
     public double getArea() {
          return r*r*PI;
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day05_object;
public class CircleBeanMain {
     public static void main(String[] args) {
          //반지름이 1,2,3,4,5 인 5개의 CircleBean객체를 만들고
          //각 CircleBean의 넓이를 출력하고
          //총 면적을 출력하시오
          //배열로 구하시오
          
          //배열은 선언, 생성, 초기화가 되어야함. 그 안에 값이 들어있어야 함.
          CircleBean[]arr=new CircleBean[5]; //선언&생성
          for(int i=0;i<arr.length;i++) {
              arr[i]=new CircleBean(i+1); //초기화. new해서 CircleBean이 각 방마다 만들어졌단 얘기. 1,2,3,4,5값을 가짐
          }
          double hap=0;
          for(int i=0;i<arr.length;i++) {
              System.out.println(arr[i].getArea());
              hap+=arr[i].getArea();
          }
          System.out.println("총 면적: "+hap);
     }
}

 


  • 성적입력 메뉴 클래스, 성적 입력 클래스, 출력 클래스와 총점으로 석차구하기 (Teacher, StudentBean, ScoreMain)
  • TwoArrayScore을 3개의 클래스로 나눈 것. 2차원 배열의 행들을 한 덩어리로 묶어서 1차원배열의 값으로 생각.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package day05_object;
import java.util.Scanner;
public class Teacher {
     Scanner sc=new Scanner(System.in);
     StudentBean[] arr=new StudentBean[50];
     int cnt; //멤버변수의 int는 초기값이 0이다.
     
     public void showMenu() {
          System.out.println("선택하세요");
          System.out.println("1.데이터입력");
          System.out.println("2.전체보기");
          System.out.println("3.종료");
          System.out.println("선택>>");
     }
     
     public void inputData() {
          System.out.println("성적입력 시작>>");
          System.out.print("이름>>");
          String name=ScoreMain.sc.next();
          System.out.print("국어>>");
          int kor=ScoreMain.sc.nextInt();
          System.out.print("영어>>");
          int eng=ScoreMain.sc.nextInt();
          System.out.print("수학>>");
          int math=ScoreMain.sc.nextInt();
          //배열에 StudentBean 객체 넣기
          arr[cnt] = new StudentBean(name, kor, eng, math);
          cnt++;
     }
      public void rankMethod() { //석차 구하는 메소드
          for(int i=0;i<cnt-1;i++) {
              for(int j=i+1;j<cnt;j++) {
                   if(arr[i].getTotal()>arr[j].getTotal()) {
                        arr[j].setRank(1); //arr[j]의 rank에 1을 더한다.
                   }else if(arr[i].getTotal()<arr[j].getTotal()) {
                        arr[i].setRank(1); //arr[i]의 rank에 1을 더한다.
                   }
              }
          }
     }
     
     public void viewData() {
          rankMethod();
int sum=0; //지역변수는 반드시 초기값이 필요.
          System.out.println("-----학생 성적 보기------");
          System.out.println("이름\t총점\t평균\t석차");
          for(int i=0;i<cnt;i++) {
              System.out.print(arr[i].name+"\t");
              System.out.print(arr[i].getTotal()+"\t");
              System.out.print(arr[i].getAvg()+"\t");
              System.out.print(arr[i].rank+"\n");
              }
          System.out.println("학급 총점: "+sum);
System.out.println("학급 평균: "+sum/cnt);
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day05_object;
public class StudentBean {
     String name;
     int kor, eng, math;
     int rank=1;
     
     public StudentBean(String name, int kor, int eng, int math) {
          this.name=name;
          this.kor=kor;
          this.eng=eng;
          this.math=math;
     }
     
     public int getTotal() {
          return kor+eng+math;
     }
     
     public double getAvg() {
          return getTotal()/3;
     }
     
     public void setRank(int rank) {
          this.rank+=rank;
     }
     
     
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day05_object;
import java.util.Scanner;
public class ScoreMain {
     static Scanner sc=new Scanner(System.in);
     
     public static void main(String[] args) {
          Teacher t1=new Teacher();
          while(true) {
              t1.showMenu();
              int num=sc.nextInt();
              switch(num) {
              case 1 : t1.inputData(); break;
              case 2 : t1.viewData(); break;
              case 3 : System.out.println("종료");
                             System.exit(0);
              default : System.out.println("입력오류");
              }
          }
          
     }
}

 

  • Car 클래스 생성하고 종류, 색상, 속도 출력하기 (Car)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package day04;
public class Car {
    String carKind;
    String carColor;
    int speed;
    
    //생성자. 반드시 클래스 이름으로 만들어야함. void가 있으면 생성자가 아니라 메소드라 생각하기때문에 없애야함.
    //인자가 없는 생성자를 디폴트 생성자라고 함. 디폴트 생성자만 사용할때는 인자 생략가능. 하지만 다른 생성자가 있을 때는 생략 불가능.
    //그래서 아무런 하는 일이 없더라도 디폴트 생성자를 하나 만들어줌.
    //오버로딩. 생성자 오버로딩. 생성자들의 이름이 같은데 들어가는 인자의 개수나 유형이 다를때.
    
    public Car() {
        System.out.println("디폴트 생성자");
    }
    public Car(String carColor, String carKind) { //매개변수가 있는걸 썼을때 디폴트 생성자 생략 불가능.
        this.carColor=carColor;
        this.carKind=carKind;
        System.out.println("인자있는 생성자");
    }
    
    public void speedUp(int s) {
        speed+=s;
    }
    
    public void speedDown(int speed) { //speed는 지역변수를 의미.
        this.speed-=speed; //this는 자기 자신의 객체를 가리킴. 6번의 speed. this.speed는 멤버변수를 의미
    }
    
    public void stop() {
        speed=0;
    }
    
    public static void main(String[]args) {
        Car mycar = new Car(); //참조변수. 레퍼런스 변수. 객체는 주소값을 가진다. 주소값을 찾아가면 객체가 가지는 변수들을 접근할 수 있다.
        mycar.carKind="소나타";
        mycar.carColor="흰색";
        mycar.speedUp(100); //괄호가 있으니까 메서드로 선언. 괄호 안에 값이 있으므로 speedUp의 함수안에는 정수형 인수가 들어가야함.
        System.out.println("속도: "+mycar.speed);
        System.out.println("color: "+mycar.carColor);
        mycar.stop();
        System.out.println("속도: "+mycar.speed);
        
        Car c1=new Car();
        c1.carKind="뉴카";
        c1.carColor="검은색";
        c1.speedUp(80);
        System.out.println(c1.carKind+" 속도: "+c1.speed);
        c1.speedDown(50);
        System.out.println(c1.carKind+" 속도: "+c1.speed);
        System.out.println(c1);
        System.out.println(mycar);
        
        Car c2=new Car("분홍색","내차"); //앞에 Car는 클래스. 뒤에 Car는 생성자. 초기값으로 분홍색, 내차라는 초기값을 가짐. 아예 차가 나올때부터 세팅.
        //생성자=멤버변수 초기화
        System.out.println(c2.carColor);
    }
}

 

 

  • Bank 클래스의 생성자, 멤버변수, 지역변수, 참조변수들..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package day04;
public class Bank {
    String name; //이름 멤버변수 (전역변수)
    int money; //잔액
    
    //생성자는 항상 클래스 바로 밑에 만들기
    public Bank() {
    }
    
    public Bank(String name, int money) {
        this.name=name; //앞의 name은 4번의 name, 뒤의 name은 12번의 name.
        this.money=money;
        System.out.println(name+" 님의 잔액은 "+money+"원 입니다.");
    }
            
    //입금. 잔액에다가 입금한 만큼의 돈을 더하는 것.
    public void inputMoney(int a) { //don은 지역변수
        money+=a;
    }
    //출금
    public void outputMoney(int b) {
        if(money<b) {
            System.out.println("잔액부족");
            return//돌려줄 값이 없는 return은 break의 의미. if else와 똑같은 말
        }
        money-=b;
    }
    //잔액확인
    public void getMoney() {
        System.out.println(name+" 님의 잔액은 "+money+"원 입니다.");
    }
    
    public static void main(String[]args) {
        Bank b1=new Bank();
        b1.name="홍길동";
        b1.inputMoney(5000);
        b1.getMoney();
        b1.outputMoney(3000);
        b1.getMoney();
        
        Bank b2=new Bank();
        b2.name="이순신";
        b2.inputMoney(10000);
        b2.getMoney();
        b2.outputMoney(20000); //잔액부족
        b2.getMoney(); //이순신님 10000원
        
        Bank b3=new Bank("강감찬",20000);
        Bank b4=new Bank("유관순",10000);
        
    }
}

 

 

  • 클래스를 이용하여 구구단 출력 (Gugudan)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package day04;
public class Gugudan {
    int dan; //멤버변수
    
    public Gugudan(int dan) { //보통 생성자는 초기화만 시킨다. 
디폴트 생성자는 굳이 필요없으면 안만들어도 됨.
        this.dan=dan;
    }
    
    public void viewData() { //구구단 출력
        System.out.println(dan+"단");
        for(int i=1;i<10;i++) { 
            System.out.println(dan+"*"+i+"="+(dan*i));
        }
    }
    public static void main(String[] args) {
    Gugudan g1=new Gugudan(5);
    g1.viewData();
    /*
     * 5*1=5
     * 5*2=10
     *
     * 5*9=45
     */
    Gugudan g2=new Gugudan(7);
    g2.viewData();
    
    Gugudan g3=new Gugudan(9);
    g3.viewData();
    }
}

 

  • 입력받고 싶은 단을 입력, 구구단 출력
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package day04;
import java.util.Scanner;
public class Gugudan {
    int dan; //멤버변수
    
    public Gugudan(int dan) { //보통 생성자는 초기화만 시킨다. 디폴트 생성자는 굳이 필요없으면 안만들어도 됨.
        this.dan=dan;
    }
    
    public void viewData() { //구구단 출력
        System.out.println(dan+"단");
        for(int i=1;i<10;i++) { 
            System.out.println(dan+"*"+i+"="+(dan*i));
        }
    }
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("단 입력");
    int dan2=sc.nextInt();
    
    Gugudan gn=new Gugudan(dan2);
    gn.viewData();
        
    Gugudan g1=new Gugudan(5);
    g1.viewData();
    /*
     * 5*1=5
     * 5*2=10
     *
     * 5*9=45
     */
    Gugudan g2=new Gugudan(7);
    g2.viewData();
    
    Gugudan g3=new Gugudan(9);
    g3.viewData();
        
    }
}
cs

 

  • 클래스를 이용하여 TV의 종류 설명 (TV)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day04;
public class TV {
    String name; //멤버변수
    int year, inch; //멤버변수
    
    public TV(String name,int year, int inch) {  //생성자. 생성자는 void쓰면 안됨.
        this.name=name;     //자신의 멤버변수name에 지역변수name을 받음.
        this.year=year;
        this.inch=inch;
    }
    
    public void show() {
        System.out.println(name+"에서 만든 "+year+"년 형 "+inch+"인치 TV");
    }
        
    public static void main(String[] args) {
        TV tv=new TV("LG",2020,60);             //앞의 TV는 클래스. 뒤에 TV는 생성자.
        tv.show(); //LG에서 만든 2020년형 60인치 TV
        
        TV mytv=new TV("삼성"2019,55);
        mytv.show(); //삼성에서 만든 2019년형 55인치 TV
        
        
    }   
}
cs

 

  • Main함수 이용해서 다른 클래스의 출력값 가져오기 (PersonMain, Person)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day04;
public class PersonMain {
    
    public static void main(String[] args) {
        Person p1=new Person(); //여기는 PersonMain클래스 이므로 Person클래스를 만들어서 Person생성자를 만들면 됨.
        p1.name="홍길동";
        p1.addr="부산";
        p1.study();
        
        Bank b=new Bank("김자바"5000); //필요하면 언제든지 부를 수 있음. 재사용성.
        b.getMoney();
        
        Baby baby=new Baby();
        baby.name="애기";
        baby.smile(); //String의 초기값은 null.
        
        Baby baby1=new Baby("김애기");
        baby1.cry();
        
        //구구단 10단을 출력
        Gugudan g10=new Gugudan(10);
        g10.viewData();
        
    }
}
cs

 

  • Person 클래스
1
2
3
4
5
6
7
8
9
10
11
package day04;
public class Person {
    String name;
    String addr;
    
    //Person생성자에 인자가 없으므로 생략가능.
    
    public void study() {
        System.out.println(name+" 공부한다.");
    }
}
cs

 

  • Main함수 이용해서 다른 클래스의 출력값 가져오기 (StudentMain, StudentSunjuk)
1
2
3
4
5
6
7
8
9
package day04;
public class StudentMain {
    public static void main(String[] args) {
        StudentSunjuk s1=new StudentSunjuk("홍길동",100,80,70);
        s1.getTotal(); //홍길동님의 총점??
        System.out.println(s1.getAvg()); //홍길동님의 평균?? s1.getAvg()을 수행한 결과값이 나오길 원함. return을 통해 돌려받은 값을 출력.
        
    }
}
cs

 

  • StudentSunjuk 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package day04;
public class StudentSunjuk {
    String name;
    int kor, math, eng;
    
    public StudentSunjuk(String name, int kor, int math, int eng) {
        this.name=name; //name을 멤버변수로 만들어주는 작업.
        this.kor=kor;
        this.math=math;
        this.eng=eng;
    }
    
    public void getTotal() {
        System.out.println(name+" 총점: "+(kor+math+eng));
    }
    
    public String getAvg() { 
    //return 값이 있으면 void는 빼고 데이터타입을 적어줌. 
    //문자+숫자이므로 문자형 String을 적어줌.
        return (name+" 평균: "+(kor+math+eng)/3); //return을 적어야 결과값을 StudentMain으로 돌려줄 수 있음.
    }
}

 

  • SongMain과 Song 클래스를 구분하여 '1978년 스웨덴 국적의 ABBA가 부른 Dancing Queen' (SongMain, Song)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package day04;
public class SongMain {
     public static void main(String[] args) {
           
           Song s1=new Song(1978,"스웨덴","ABBA","Dancing Queen");
           s1.show();
           //1978년 스웨덴 국적의 ABBA가 부른 Dancing Queen
           
           Song s2=new Song(2001"미국","Avril Lavigne","Sk8ter Boi");
           s2.show();
           
           Song s3=new Song(2011"영국","Amy Winehouse","Back to Black");
           s3.show();
           
     }
}

 

 

  • Song 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day04;
public class Song {
     int year;
     String country, artist, title;
     
     //생성자
     public Song(int year, String country, String artist, String title) {
           this.year=year;
           this.country=country;
           this.artist=artist;
           this.title=title;
     }
     
     public void show() {
           System.out.println(year+"년 "+country+" 국적의 "+artist+"(이)가 부른 "+title);
     }
     
     
     
}

 

 

  • Triangle, TriangleMain 분리하고 삼각형의 면적 구하기. 밑변과 높이의 인수가 달라졌을때의 면적 구하기. (Triangle, TriangleMain)
1
2
3
4
5
6
7
8
9
10
11
12
package day04;
public class TriangleMain {
    public static void main(String[] args) {
        Triangle tr=new Triangle(10.2,17.3);
        System.out.println("삼각형의 면적: "+tr.getArea());
        
        tr.setBottom(7.5);
        tr.setHeight(11.2);
        System.out.println("삼각형의 면적: "+tr.getArea());
        
    }
}

 

 

  • 삼각형의 밑변과 높이를 입력하여 넓이 구하기. 사용자가 종료하기 전까지 계속 구하도록 하기.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package day04;
import java.util.Scanner;
public class TriangleMain {
    public static void main(String[] args) {
        Triangle tr=new Triangle(10.2,17.3);
        System.out.println("삼각형의 면적: "+tr.getArea());
        
        tr.setBottom(7.5);
        tr.setHeight(11.2);
        System.out.println("삼각형의 면적: "+tr.getArea());
        
        Scanner sc=new Scanner(System.in);
        while(true) {
            System.out.println("1.삼각형 넓이 구하기 2.종료");
            int num=sc.nextInt();
            if(num==2) {
                System.out.println("프로그램 종료");
                break;
            }
            else if(num==1) {       
            System.out.println("삼각형 밑변>>");
            double bottom=sc.nextDouble();
            System.out.println("삼각형 높이>>");
            double height=sc.nextDouble();
            
            Triangle tr1=new Triangle(bottom,height);
            System.out.println("입력삼각형의 면적: "+tr1.getArea());
            }
            else {
                System.out.println("입력오류");
            }
        }
        
        
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package day04;
public class Triangle {
    double bottom, height;
    
    public Triangle(double bottom, double height) {
        this.bottom=bottom;
        this.height=height;
    }
    
    public double getArea() {
        return(bottom*height/2);
    }
    
 public void setBottom(double bottom) {
        this.bottom=bottom;
    }
    
    public void setHeight(double height) {
        this.height=height;
    }
}
  • 10개의 수를 입력받아 배열에 넣고 그 배열의 합계와 가장 작은 수 구하기 (Exam01)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package day04;
import java.util.Scanner;
public class Exam01 {
    public static void main(String[] args) {
        //10개의 수를 입력받아 배열에 넣고
        //그 배열의 합계와 가장 작은 수 구하기
        
        Scanner sc=new Scanner(System.in);
        System.out.println("10개의 양수 입력>>");
        
        int []arr=new int[10];
        
        int sum=0;
        
        for(int i=0;i<10;i++) {
            arr[i]=sc.nextInt();
            sum+=arr[i];
        }
        System.out.println("합계: "+sum);
        
        int min=arr[0];
        for(int i=0;i<10;i++) {
            if(min>arr[i]) {
                min=arr[i];
            }
        }
        System.out.println("최소값: "+min);
        
        for(int a:arr) {
            System.out.print(a+"\t");
        }
        System.out.println();
    }
}

 

 

  • 난수를 배열에 입력하되 들어갈 위치를 랜덤하게 정하고 1부터 100이하의 수를 넣으시오. 단, 값이 이미 들어가 있으면 넣지 않는다. (Exam02)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package day04;
public class Exam02 {
    public static void main(String[] args) {
        //난수를 배열에 입력하되
        //들어갈 위치를 랜덤하게 정하고
        //1부터 100이하의 수를 넣으시오
        //단, 값이 이미 들어가 있으면 넣지 않는다.
        
        int []arr=new int[5]; //0 0 0 0 0
        int n=0;
        while(n<arr.length){ //배열의 길이 만큼 반복한다.
            int col=(int)(Math.random()*5); //배열위치를 랜덤하게 정한다.
            if(arr[col]!=0) { //이 위치에는 이미 값이 들어갔음. 그럼 다시 while문을 돌아서 "배열의 위치"를 정한다.
                continue;
            }else { //배열에 들어간 값이 0이라면 (=값이 없다면) 1에서 100이하의 난수를 발생.
                arr[col]=(int)(Math.random()*100)+1//1에서 100이하이므로 0이 나왔을때 1을 더해주는 것.
                n++;
            }
        }
        
        for(int i=0;i<arr.length;i++) {
            System.out.print(arr[i]+"\t");
        }
        
        
    }
}
cs

 

 

  • Student 클래스를 선언하고 속성과 행위 표현 (멤버변수, 메소드) (Student)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package day04;
public class Student { //클래스를 선언. 속성과 행위를 표현할 수 있고, 속성은 멤버변수, 행위는 메소드.
    int StudentID; //학번
    String name; //이름
    int grade; //학년
    String address; //주소
    
    //공부하다 라는 행위를 표현하고 싶다. 그 행위를 프로그램에서는 함수라고 함. 객체지향의 함수는 메소드.
    public void study() { //함수는 반드시 괄호가 있음
        System.out.println(name+"공부하다");
    }
    
    public void play() {
        System.out.println(name+"운동하다");
    }
    public static void main(String[] args) { //실행은 항상 main함수 부터
        Student s1=new Student(); //Student 클래스 안에 s1이라는 객체 생성
        s1.StudentID=100//누구의 학번인지 표현해야하므로 점(.)을 찍는게 중요.
        s1.name="홍길동";
        s1.grade=1;
        s1.address="부산";
        System.out.println("s1의 이름: "+s1.name);
        
        Student s2=new Student();
        s2.StudentID=200;
        s2.name="이순신";
        s2.grade=4;
        s2.address="서울";
        System.out.println("s2의 이름: "+s2.name);
        
        System.out.println(s1.name+"의 주소: "+s1.address);
        
        //이름이 강감찬이고 3학년, 인천에 사는 학생 s3을
        //생성하고 s3의 이름과 주소를 출력하시오.
        Student s3=new Student();
        s3.name="강감찬";
        s3.grade=3;
        s3.address="인천";
        System.out.println("s3 이름: "+s3.name);
        System.out.println("s3 주소: "+s3.address);
        
        //홍길동이 공부하다
        s1.study();
        //강감찬이 공부하다
        s3.study();
        
        //학생이라는 클래스를 만들때 학번, 이름, 학년, 주소를 만들었고
        //공부하다라는 행위까지 표현.
        
        //학생이라는 클래스를 수정하는데 play()함수를 가지고 있고..
        //여기에서 이름 운동한다라는 값을 출력하시오
        s1.play();
 
        
    }
}
cs

 

 

  • Baby 클래스를 선언하고 속성값에 이름과 나이. 웃는다와 운다 행위 표현. (Baby)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package day04;
public class Baby { //클래스는 보통 대문자로 시작하게끔 표현
    String name;
    int age;
    
    //웃는다
    //운다
    public void smile() {
        System.out.println(name+"이 웃는다.");
    }
    
    public void cry() {
        System.out.println(name+"이 운다.");
    }
    public static void main(String[] args) {
        //Baby 객체 b1을 만들고
        //이름 베이비1 나이 2
        //베이비1 이 웃는다
        Baby b1=new Baby();
        b1.name="베이비1";
        b1.age=2;
        b1.smile();
        
        //Baby 객체 b2을 만들고
        //이름 베이비2 나이 1
        //베이비2 이 운다
        Baby b2=new Baby();
        b2.name="베이비2";
        b2.age=1;
        b2.cry();
        
    }
}

 

 

  • 사칙연산하는 클래스 만들고 매개변수를 할당받아 사칙연산하기 (Sachik)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package day04;
public class Sachik {
    //덧셈
    public void sum(int a, int b) {
        System.out.println("덧셈: "+(a+b));
    }
    //뺄셈
    public void sub(int a, int b) {
        System.out.println("뺄셈: "+(a-b));
    }
    //곱셈
    public void mul(int a, int b) {
        System.out.println("곱셈: "+(a*b));
    }
    //나눗셈
    public void div(int a, int b) {
        System.out.println("나눗셈: "+(a/b));
    }
    
    public static void main(String[] args) {
        Sachik s1=new Sachik();
        s1.sum(10,5); //함수를 부를때 값을 전달할 매개변수. 5번으로 가서 각각 순서대로 정수형 변수 a,b에 전달됨.
        s1.sub(20,10);
        s1.mul(3,5);
        s1.div(9,3);
        
        
    }
}

 

 

  • 사칙연산하는 클래스 만들고 매개변수를 할당받아 사칙연산하기-리턴값을 주고 메인함수에서 나눗셈의 값 출력 (Sachik)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package day04;
public class Sachik {
    //덧셈
    public void sum(int a, int b) {
        System.out.println("덧셈: "+(a+b));
    }
    //뺄셈
    public void sub(int a, int b) {
        System.out.println("뺄셈: "+(a-b));
    }
    //곱셈
    public void mul(int a, int b) {
        System.out.println("곱셈: "+(a*b));
    }
    //나눗셈
    public int div(int a, int b) { //void는 리턴값이 없다는 뜻. 리턴이 있으므로 그 자료형을 void대신에 적어준다.
        //System.out.println("나눗셈: "+(a/b));
        return a/b; //return은 값을 돌려준다는 것.
    }
    
    public static void main(String[] args) {
        Sachik s1=new Sachik();
        s1.sum(10,5); //함수를 부를때 값을 전달할 매개변수. 5번으로 가서 각각 순서대로 정수형 변수 a,b에 전달됨.
        s1.sub(20,10);
        s1.mul(3,5);
        //s1.div(9,3);
        System.out.println(s1.div(20,5));
    }
}

 

 

  • Bank클래스 만들고 입금, 출금, 잔액확인 메소드를 만들기. 객체 b1생성하고 이름을 홍길동이라 하기. 입금, 출금하고 잔액확인 (Bank)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package day04;
public class Bank {
    String name; //이름 멤버변수 (전역변수)
    int money; //잔액
    
    //입금. 잔액에다가 입금한 만큼의 돈을 더하는 것.
    public void inputMoney(int don) { //don은 지역변수
        money+=don;
    }
    //출금
    public void outputMoney(int don) {
        money-=don;
    }
    //잔액확인
    public void getMoney() {
        System.out.println(name+" 님의 잔액은 "+money+"원 입니다.");
    }
    
    public static void main(String[]args) {
        //Bank 객체 b1을 만들고
        //b1의 이름은 홍길동
        //홍길동이 5000원을 입금하고 잔액을 확인함
        //홍길동님의 잔액은 5000원입니다.
        Bank b1=new Bank();
        b1.name="홍길동";
 
         b1.inputMoney(5000);
        b1.getMoney();
        
        //홍길동이 3000원을 출금하고 잔액확인
        //홍길동님의 잔액은 2000원 입니다.
        b1.outputMoney(3000);
        b1.getMoney();
   }
}

 

  • 왼쪽정렬 역삼각형 별찍기 (Exam01)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package day03;
public class Exam01 {
    public static void main(String[] args) {
        
        for(int i=9;i>0;i-=2) {
            for(int j=1;j<=i;j++) {
                System.out.print("*");
            }System.out.print("("+i+")");
            System.out.println();
        }
                
        for(char i='I';i>='A';i-=2) {
            for(char j='A';j<=i;j++) {
                System.out.print(j);
            }
            System.out.println("("+i+")");
       }
for(char i='I';i>='A';i-=2) {
            for(char j='A';j<=i;j++) {
                System.out.print((char)(j+1)); //char형으로 표시해서 출력해 달라고 하는 캐스팅 (형변환)
            }
            System.out.println("("+i+")");
        }
        System.out.println("======");
    }
}
cs

 

 

  • ********...z 그 다음 행 ******...yz 만들기 (Exam01)
1
2
3
4
5
6
7
8
9
10
for(char i='z';i>='a';i--) {
            for(char j='a';j<='z';j++) {
                if(j>=i) {
                    System.out.print((char)j);  
                }else {
                    System.out.print("*");
                }
            }
            System.out.println();
        }

 

 

  • 1부터10까지의 합: 55, 11부터20까지의 합: 155 (Exam02)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package day03;
public class Exam02 {
    public static void main(String[] args) {
        
        for(int i=1;i<=100;i+=10) {
            int sum=0//sum을 초기화시켜야 다시 11부터 20까지, 21부터 30까지 각각 더할 수 있음.
            int j;
            for(j=i;j<i+10;j++) {
                sum+=j;
            }
            System.out.println(i+"부터"+(j-1)+"까지의 합: "+sum);
        }
        System.out.println();
    }
}

 

 

  • 1차원 배열 선언 (Exam03)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package day03;
public class Exam03 {
    public static void main(String[] args) {
        
        int[] arr = new int [5]; //배열 arr 선언
        arr[0=100;
        arr[1=200;
        arr[2=300;
        arr[3=400;
        arr[4=500;
        System.out.println(arr[3]); //400
        
        
        int[] test =new int[20]; //배열은 반드시 길이를 할당해줘야함. int형 배열은 0으로 초기화.
        System.out.println(test[5]); //0
        for(int i=0;i<test.length;i++) { //배열 0에 0, 1에 1 저장.
            test[i]=i;
        }
        System.out.println("test[5]: "+test[5]);
        test[5]=3000//test[5]값을 3000으로 변경
        System.out.println("test[5]: "+test[5]);
        
        //int [] arr= new int[5]; // 0 0 0 0 0 이라는 배열이 만들어짐
        //1 2 3 4 5 라는 값으로 배열을 만들고 싶다면
        int[]arr1= new int[5];
        for(int i=0;i<arr1.length;i++) { //"배열명.length"는 배열의 길이를 반환함.
            arr1[i]=i+1;
        }
        for(int i=0;i<arr1.length;i++) {
            System.out.println("arr1["+i+"]:"+arr1[i]);
        }
        
        int[]arr2 = {1,2,3,4,5,6,7};
        for(int i=0;i<arr2.length;i++) {
            System.out.println("arr2["+i+"]:"+arr2[i]);
        }
        
        String[]str = {"one","two","three"};
        for(int i=0;i<str.length;i++) {
            System.out.println("str["+i+"]:"+str[i]);
        }
        
        String[]str1= new String[3];
        str1[0]="one";
        str1[1]="tow";
        str1[2]="three";
        for(int i=0;i<str1.length;i++) {
            System.out.println("str1["+i+"]:"+str1[i]);
        }
    }
}
cs

 

 

  • 원하는 개수를 입력, 그 개수 만큼 수를 입력, 합계와 입력데이터 출력 (배열 이용) (Exam04)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day03;
import java.util.Scanner;
public class Exam04 {
    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        System.out.println("입력 갯수>>");
        int cnt=sc.nextInt();
        
        System.out.println("데이터 입력>>");
        int sum=0;
                
        int[]arr= new int[cnt];
        
        for(int i=0;i<cnt;i++) { 
            arr[i]=sc.nextInt(); 
            sum+=arr[i];            
        }
        System.out.println("합계: "+sum);
        for(int i=0;i<cnt;i++) {
            System.out.println("입력 데이터: "+arr[i]);
            //for문 안에 안넣으면 오류발생. 배열 arr의 주소 0부터 입력 개수cnt 전까지 차례대로 출력함.
        }
    }
}
cs

 

 

  • 배열의 최대값, 최대값의 위치, 배열 데이터들의 합계 구하기 (Exam05)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day03;
public class Exam05 {
    public static void main(String[] args) {
        
        int[] data= {10,5,90,100,250,30,77};
        
        //최대값을 구하기
        //최대값의 위치 구하기
        
        int max=data[0]; //0번째 데이터가 제일 크다고 max변수를 선언
        int maxPos=0;
        int sum=0;
                        
        for(int i=0;i<data.length;i++) {
            sum+=data[i];
            if(max<data[i]) {
                max=data[i];
                maxPos=i+1//배열의 주소는 0부터지만 앞에서부터 개수를 센다고 생각했을때 최대값 250은 5번째에 있다.
            }
        }System.out.println("최대값: " +max);
        System.out.println("최대값의 위치: "+maxPos);
        System.out.println("배열의 합계: "+sum);
        System.out.println("배열의 평균: "+(float)sum/data.length);
    }
}
cs

 

 

  • 찾는 수를 입력, 그 수의 위치 구하기. 없으면 없다고 출력 (Exam05)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Scanner sc=new Scanner(System.in);              
        System.out.println("찾는 수를 입력하세요>>");
        int search=sc.nextInt();
        boolean flag=false//변수를 선언
        
        for(int i=0;i<data.length;i++) {
            if(search==data[i]) {
                System.out.println("찾는 수 "+search+" :"+(i+1));
                flag=true//변수의 참 여부에 따라 조건을 설정->출력문 하나만 나오도록.
            }
        }
        if(flag==false) {
            System.out.println("찾는 수"+search+"없음");
        }
cs

 

 

  • 길이가 10인 배열 선언, 난수 발생시켜서 배열에 할당, 난수가 0일 경우 다시 난수 발생시키기, 배열 출력 (Exam06)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package day03;
public class Exam06 {
    public static void main(String[] args) {
        
        //난수 발생. double 형을 돌려줌. 부동 소수점. 0.0에서 1.0사이. 정수가 필요하다면 곱한 뒤에 int형으로 바꿔주기
        /*System.out.println((int)(Math.random()*50));
         * 크기가 10인 배열을 만들고
         * 0에서 50사이 난수를 발생시켜
         * 0이 아닌 값을 배열에 넣으세요 -> 난수가 0일때는 다시 난수 발생
         * 중복허용
         */
        
        int[] arr=new int[10]; //길이 10인 배열 선언
        int n=0;
        while(n<arr.length){ //배열크기 10번 반복
            int r=(int)(Math.random()*50); //난수발생을 변수 r에 할당
            if(r==0) { //난수가 0인지 판단
                continue//난수가 0이라면 다시 올라감. 다시 반복=>while의 continue라는 걸 기억하기
            }else { //난수가 0이 아님
                arr[n]=r;
                n++;
            }
        }
        for(int i=0;i<arr.length;i++) {
            System.out.print(arr[i]+"\t");
        }
    }
}
cs

 

 

  • 2차원 배열을 입력하고 출력하는법 (Exam07)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package day03;
public class Exam07 {
    public static void main(String[] args) {
        
        int[][] arr=new int[3][4];
        arr[0][0]=1;
        arr[0][1]=2;
            
        int[][] a= {{1,2,3,4},{11,22,33,44},{111,222,333,444}};
        System.out.println(a[1][2]); //33
        for(int i=0;i<a.length;i++) { //a.length는 중괄호가 "3개"=행의 길이
            for(int j=0;j<a[i].length;j++) {   //a[i].length는 {1,2,3,4}의 길이. 2차원 배열 열의 길이.
                System.out.print(a[i][j]+"\t"); //2차원 배열 출력
            }System.out.println();
        }
        
    }
}
cs

 

 

  • 원하는 금액을 입력, 배열을 이용하여 권종별로 몇 장이 필요한지 출력 (Exam08)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day03;
import java.util.Scanner;
public class Exam08 {
    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);
        System.out.println("금액입력>>"); //65589
        int unit[]= {50000,10000,1000,500,100,50,10,1};
        int money=sc.nextInt();
            
        for(int i=0;i<unit.length;i++) {
            if(money/unit[i]>0) {  //몫을 먼저 구한뒤에 나머지를 계산해야 하니까 %연산자 보다 /연산자가 더 먼저 나와야 함.
                System.out.println(unit[i]+":"+money/unit[i]); //result값을 따로 주지 않고 money/arr[i]로 표현.
                money=money%unit[i];
            }
        }
        
        
    }
}
cs
  • Switch 문으로 국어, 영어, 수학 점수 입력하고 총점, 평균, 학점 출력 (day02 패키지의 Exam01 클래스 )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package day02;
import java.util.Scanner;
public class Exam01 {
    public static void main(String[] args) {
        Scanner sc = new Scanner (System.in);
        System.out.println("국어점수 입력>>");
        int kor=sc.nextInt();
        System.out.println("영어점수 입력>>");
        int eng=sc.nextInt();
        System.out.println("수학점수 입력>>");
        int math=sc.nextInt();
        int total=(kor+eng+math);
        int avg=(kor+eng+math)/3;
        
        String grade="";
        
        switch(avg/10) { //A학점, B학점, C학점의 공통점: 점수를 10으로 나눴을때 몫이 9, 8, 7...
        case 9 :
            grade="A";break;
        case 8 :
            grade="B";break;
        case 7 :
            grade="C";break;
        default :
            grade="F";break;
        }
        System.out.println("총점: " +total);
        System.out.println("평균: " +avg);
        System.out.println("학점: " +grade);
    }    
}

 

 

  • 금액 입력하고 만원 권, 천원 권 몇 장인지 출력하기 (Exam02)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package day02;
import java.util.Scanner;
public class Exam02 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("금액을 입력하세요");
        int money = sc.nextInt();
        
        int result = money/10000;
        System.out.println("만원권: " +result +"장");
        
        money = money%10000;
        result = money/1000;
        
        System.out.println("천원권: " +result +"장");
    }
}

 

 

  • 단을 입력받아 해당되는 단의 구구단 출력 (Exam03)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package day02;
import java.util.Scanner;
public class Exam03 {
    public static void main(String[] args) {
        /*
        for(int i=1;i<6;i++) { //i=1초기값,2,3,4,5 6은 i<6조건을 만족하지 않기 때문에 for문 빠져나옴.
            System.out.println(i+ ":안녕하세요");
        }
        System.out.println("========");
        
        for(int i=5;i>0;i--) {
            System.out.println(i+ ":안녕하세요");
        }
        System.out.println("========");
        
        for(int j=1;j<10;j++) {
            System.out.println("2*"+ j+ "=" +2*j);
        }   
        System.out.println("========");
   //짝수만 출력하기 ver.1
        for(int i=1;i<=10;i++) {
            if(i%2==0) {
                System.out.println(i);
            }
        }
        System.out.println("=======");
        //짝수만 출력하기 ver.2
        for(int i=2;i<=10;i+=2) {
            System.out.println(i);
        }
        */ 
        //단을 입력받아 해당되는 단의 구구단 출력
        Scanner sc=new Scanner(System.in);
        System.out.println("단을 입력>>");
        int d=sc.nextInt();
        
        for(int j=1;j<10;j++) {
            System.out.println(d+"단 "+d+"*"+j+"="+(d*j));
        }
    }
}

 

  • 1부터 100까지의 합 구하고 10번만 출력하기 (Exam04)
1
2
3
4
5
6
7
8
9
10
11
12
13
package day02;
public class Exam04 {
    public static void main(String[] args) {
                
        int hap=0;
        for(int i=1;i<=100;i++) {
            hap+=i; //1부터 100까지의 합을 hap변수로 구함
            if(i%10==0) { //i가 10으로 나누어 떨어질때: 10,20,30,...100까지. 그때만 hap을 출력하겠다는 의미.
                System.out.println("1부터"+i+"까지의 합 "+hap);
            }
        }
    }
}
cs

 

  • 1+2+3+4+5+6+7+8+9+10=55 형식으로 값 출력하기 (Exam04)
1
2
3
4
5
6
7
8
int s=0;
        for(int i=1;i<=10;i++) {
            s+=i;
            if(i!=10) {
                System.out.print(i+"+");
            }else {
                System.out.print(i+"="+s);
            }
cs

 

 

  • 입력할 수의 개수를 정하고, 입력한 수들을 더하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package day02;
import java.util.Scanner;
public class Exam05 {
    public static void main(String[]args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("입력할 개수>>");
        int cnt=sc.nextInt();
        
        System.out.println("데이터입력>>");
        int sum=0;
        
        for(int i=0;i<cnt;i++) { //for문 안에서 수들을 "입력"하도록 하면 처음에 정한 개수만큼만 수 입력가능. 그걸 벗어나면 자동으로 수 입력 못하게.
            int inputData = sc.nextInt();
            sum+=inputData; //입력한 수들을 자동으로 더하도록  sum변수 선언
        }
        System.out.println("합계:"+sum); //더한 값들을 출력
            
    }
}
cs

 

  • 학생 수 입력, 한 줄에 앉을 학생 수 입력 (Exam06)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package day02;
import java.util.Scanner;
public class Exam06 {
    public static void main(String[] args) {
        
        /*
        int sum=0;
        for(int i=1;i<=100;i++) {
            sum+=i;
            if(i%10==0) {
                System.out.println((i-9)+"부터"+i+"까지의 합 "+sum);
                sum=0;  //if를 한번 돌고 난 다음에 sum이 0부터 시작하도록. 합을 누적시키는게 아니라 단계별로 구하기 위해서.
            }
        }
        /*학생수와 한줄에 앉을 학생 수를 입력받아 출력하시오
         *
         */
        Scanner sc=new Scanner(System.in);
        System.out.println("학생 수를 입력>>");
        int stuCnt=sc.nextInt();
        System.out.println("한줄 인원 수 입력>>");
        int lineCnt=sc.nextInt();
        for(int i=1;i<=stuCnt;i++) {
            System.out.print(i+"\t"); //\t는 탭만큼 띄운다는 뜻
            if(i%lineCnt==0) { //i가 lineCnt 즉 한줄 인원수랑 똑같으면. 한줄에 다 찼으면
                System.out.println(); //다음 줄로 띄운다.
            }
        }
        
        /*
        int row=stuCnt%lineCnt;
        if(row==0) {
            System.out.println((stuCnt/lineCnt)+"줄 필요");
        }else {
            System.out.println(((stuCnt/lineCnt)+1+"줄 필요"));
        }
        
        */
        //삼항 연산자(조건연산자)
        
        int r=(stuCnt%lineCnt==0)? stuCnt/lineCnt:(stuCnt/lineCnt)+1;  
        System.out.println();
        System.out.println("총라인 수: "+r);
    }
}
cs

 

  • 반복문 (for, while, do~while) (Exam072)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day02;
public class Exam072 {
    public static void main(String[] args) {
        
        for(int i=1;i<6;i++) {
            System.out.print(i+"\t");
        }
        System.out.println("\n-----");
        
        int n=1;
        while(n<6) { //조건에 안맞으면 실행 안함
            System.out.print(n+"\t");
            n++;
        }
        System.out.println("\n----");
        
        //1부터 5까지 출력 do~while
        int m=1;
        do { //최소한 한번은 실행
            System.out.print(m+"\t");
            m++;
        }while(m<6);
        
    }
}

 

 

  • 1부터 10까지 홀수의 합 구하기 (Exam08)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package day02;
public class Exam08 {
    public static void main(String[] args) {
        //1부터 10까지 홀수의 합을 구하기
        
        int i=0;
        int sum=0;
        while (i<10) {
            i++;
            if(i%2==1) {
                sum+=i;
            }
        }
        System.out.println("결과: "+sum);
        System.out.println("======");
        
        int hap=0;
        for(int j=1;j<=10;j++) {
            if(j%2!=1continue;
            hap+=j;
        }
        System.out.println("continue 결과: "+hap);
        System.out.println("======");
        /*j가 1일때 j%2!=1이란 조건에 안걸림. continue 안걸리고 hap에 j값 더함
         * j가 2일때 j%2!=1이란 조건에 걸림. 그러면 continue만나고 다시 올라감.
         * 결국 홀수만 더하게 되는것.
         */
        
        System.out.println("결과: "+sum);
        System.out.println("======");
        
        int h=0;
        for(int k=1;k<=10;k++) {
            if(k%2!=1break;
            h+=k;
        }
        System.out.println("break 결과: "+h);
        System.out.println("======");
        /*break는 반복문을 벗어나라.
         * k가 1일때 h는 1. k가 2일때 나머지가 1이 아니므로 break를 만나서 반복문을 벗어남.
         * 그래서 h는 1밖에 안됨
         */
    
    }
}
cs

 

  • 수를 입력하고 싶은 만큼 입력하고, -1을 입력하면 그 전까지의 합계와 평균 구하기 (Exam09)
  • 입력하고 싶은 만큼 입력한다는 건 반복문 안에 nextInt()을 써야한다는 뜻. 반복문 밖에 쓰면 한번밖에 입력 못함.

  • 평균을 구하려면 개수를 구해야함. 반복할때 개수가 1씩 늘어나면 됨.

  • -1일때 합계, 평균, 개수 멈춰야함 break밑에 두기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day02;
import java.util.Scanner;
public class Exam09 {
    public static void main(String[] args) {
        //수를 입력하는데 -1이 입력되면 입력 끝.
        //입력한 수의 합계와 평균을 구하시오
        //예)10 5 6 9 -1
        Scanner sc=new Scanner(System.in);
        System.out.println("수를 입력하세요. 마지막은 -1");
        
        int sum=0;
        int cnt=0//평균을 구하려면 합계를 '입력한 수의 개수'만큼 나눠야함. 몇 번을 입력했는지 알려면 개수도 카운트 되어야함.
        
        while(true) {
            int su=sc.nextInt();
            if(su==-1break//-1을 입력하면 벗어나기.
            sum+=su; //입력한 수, su에 수를 입력 할때마다 덧셈. su가 -1이 아니라면 계속 더함.
            cnt++//-1을 입력하기 전까지 개수를 셈. su에 수를 입력 할때마다 1씩 증가.
        }
        System.out.println("합계: "+sum);
        System.out.println("입력개수: "+cnt);
        System.out.println("평균: "+sum/cnt);
        sc.close();
    }
}

 

  • 문단을 나눠 구구단 출력하기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day02;
public class Exam10 {
    public static void main(String[] args) {
        
        for(int k=2;k<=4;k++) { //이중 for문. 바깥 for가 한번 돌때 안에 for가 다 돌고 나서 바깥 for문 두번째 돔.
            for(int i=1;i<=3;i++) {
                System.out.println(k+"*"+i+"="+k*i);    
            }
            System.out.println("===");
        }
    
        
        for(int i=1;i<=9;i++) {
            for(int d=4;d<=6;d++){
                System.out.print(d+"*"+i+"="+d*i+"\t");             
            }
            System.out.println();
        }
    }   
}
cs
  • 값을 입력받고 조건에 맞게 출력하기 (홀수 짝수, 나이별 입장판별) (Exam06)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package day01;
import java.util.Scanner//java안에 util안에 Scanner를 import한다.
public class Exam06 {
    public static void main(String[] args) {
        System.out.println("수를 입력하세요>>"); //scanner 이용해서 수를 입력받아서 출력하도록 명령.
        Scanner sc = new Scanner(System.in); //new라는 키워드를 이용해 스캐너에 값 입력. 키보드로 입력하도록.
        int su = sc.nextInt(); //a라는 "문자"를 넣게되면 오류 발생
        if(su%2==0) {
            System.out.println(su+ " 짝수");
        }else {
            System.out.println(su+ " 홀수"); 
        }
        
        System.out.println("나이를 입력하세요>>");
        int age = sc.nextInt(); //정수 입력 받음.
        if(age>=20) {
            System.out.println("입장가능");
        }else if(age>=15) { //&&를 쓸 필요 없음. 이미 20보다 작기때문에 여기로 내려온 거라서. else if 가 아니라 if라면 써야함.
            System.out.println("부모님과 동반입장");
        }else {
            System.out.println("입장 불가능");
        }
    }
cs

 

  • 점수와 커트라인을 입력받고 합격, 불합격 정하기 (Exam07)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package day01;
import java.util.Scanner;
public class Exam07 {
    public static void main(String[] args) {
        System.out.println("점수를 입력하세요>>"); //점수를 입력하라는 문장을 먼저 출력하도록
        Scanner i = new Scanner(System.in); //Scanner를 써서 키보드로 수를 입력받도록
        int point = i.nextInt(); //점수 값을 변수 point에 받도록. 스캐너 이름을 동일하게.
        
        System.out.println("커트라인을 입력하세요>>"); //커트라인을 입력하라는 문장을 먼저 출력하도록
        int cutline = i.nextInt(); //커트라인 값을 변수 cutline에 받도록. 스캐너 이름 동일하게.
        if(point>=cutline) {
            System.out.println("합격");
        }else {
            System.out.println("불합격");
        }
    }
}
cs

 

  • 국어, 영어, 수학 성적을 각각 입력하고 총점, 평균, 학점 구하기 (Exam08)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package day01;
import java.util.Scanner;
public class Exam08 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("이름 입력>>");
        String name = sc.next(); //nextInt 아님. 문자를 입력받는다.
        System.out.println("국어 점수를 입력하세요>>");
        int kor = sc.nextInt();
        System.out.println("영어 점수를 입력하세요>>");
        int eng = sc.nextInt();
        System.out.println("수학 점수를 입력하세요>>");
        int math = sc.nextInt();
        
        int total = kor+math+eng; //총점
        int avg = total/3//평균은 total 나누기 3
        
        System.out.println("이름:" +name);
        System.out.println("총점:" +total);
        System.out.println("평균:" +avg);
        String grade =""//문자열 변수 grade를 만들기
        
        if(avg>=90) {
            grade="A학점";  //system.out.println("A학점") 이런식으로 계속 쓰는 거 보단 grade 이용하고 맨 밑에 한번만 출력문 적어주면 됨.
        } else if(avg>=80) {
            grade="B학점";
        } else if(avg>=70) {
            grade="C학점";
        } else {
            grade="F학점";
        }
        System.out.println(grade);
    }
}
cs

 

  • tmp변수를 써서 큰 수, 작은 수, 양수값으로 나오는 두 수의 차 구하기 (Exam09)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package day01;
import java.util.Scanner;
public class Exam09 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        /*System.out.println("첫번째 수 입력>>");
        int num1 = sc.nextInt();
        System.out.println("두번째 수 입력>>");
        int num2 = sc.nextInt();
    
        if(num1>num2){
            System.out.println("큰 수: " +num1);
            System.out.println("작은 수: " +num2);
            System.out.println("두 수의 차: " +(num1-num2));
        }else if(num1<num2){
            System.out.println("큰 수: " +num2);
            System.out.println("작은 수: " +num1);
            System.out.println("두 수의 차: " +(num2-num1));
        }else {
            System.out.println("두 수는 같다");
        }
    }
    */
    System.out.println("첫번째 수 입력>>");
        int max = sc.nextInt();
        System.out.println("두번째 수 입력>>");
        int min = sc.nextInt();
        if(min>max) {
            int tmp = max; //임시로 max의 값을 저장할 정수형 변수 tmp 선언.
            max = min; //min의 값이 max에 들어감.
            min = tmp; //아까 max의 값을 임시로 저장했던 tmp의 값이 min에 들어감.
        }
        System.out.println("큰 수: " +max);
        System.out.println("작은 수: " +min);
        System.out.println("두 수 차: " +(max-min));
    }
}
cs

 

  • 두 자리 수를 10의 자리, 1의 자리 떼어서 3,6,9 박수치기 (Exam10)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package day01;
import java.util.Scanner;
public class Exam10 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("1~99사이 정수를 입력하세요");
        int num = sc.nextInt();
        
        int a = num/10;
        int b = num%10;
        
        /*
        int c = a%3;
        int d = b%3;
                
        if((c==0)&&(d==0)) {
            System.out.println("박수짝짝");
        }else if((c==0)&&(d!=0)) {
            System.out.println("박수짝");
        }else if((c!=0)&&(d==0)) {
            System.out.println("박수짝");
        }else {
            System.out.println("박수없음");
        }
        */
        
        int cnt=0;
 
        if(a!=0&&a%3==0) {
            cnt = cnt+1;
        }
        if(b!=0&&b%3==0) {
            cnt = cnt+1;
        }
        if(cnt==2) {
            System.out.println("박수짝짝");
        }else if(cnt==1) {
            System.out.println("박수짝");
        }else {
            System.out.println("박수없음");
        }
    }
}

 

  • 전위연산, 후위연산 (Exam11)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package day01;
public class Exam11 {
    public static void main(String[] args) {
        int n1 = 5;
        int n2 = ++n1; //n1에서 1 증가한 값을 n2에 넣기.
        System.out.println("n1: "+n1); //6
        System.out.println("n2: "+n2); //6
        System.out.println("======");
        
        int n3 = n1++//6을 n3에 넣고, 빠져나오면서 n1이 7이 됨.
        System.out.println("n1: "+n1); //7
        System.out.println("n3: "+n3); //6
        System.out.println("======");
        
        int num1=7;
        int num2=--num1; //num1=6, num2=6
        int num3=num1--//num1=5, num3=6
        System.out.println("num1: "+num1); //5
        System.out.println("num2: "+num2); //6
        System.out.println("num3: "+num3); //6
        
        int a=50, b=3;
        int c;
        a++//빠져 나오면서 a=51
        ++b; //b=4
        c=a++ + ++b; //c=51+5=56 값을 계산하고 난 뒤에 빠져나오면서 a=52
        System.out.println("a: "+a); //52
        System.out.println("b: "+b); //5
        System.out.println("c: "+c); //56
        System.out.println("======");
 
        int aa=10, bb=3;
        int cc;
        --aa; //a=9
        bb++//빠져나오면서 bb=4
        cc=aa-- + ++bb; //cc=9+5=14, bb=5, aa=8
        System.out.println("aa: "+aa); //8
        System.out.println("bb: "+bb); //5
        System.out.println("cc: "+cc); //14
        
    }
}

 

  • switch문 (Exam12)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package day01;
import java.util.Scanner;
public class Exam12 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("1.자바 2.데이터베이스 3.안드로이드 4.기타");
        System.out.println("과목번호 선택>>");
        int num = sc.nextInt();
        /*
        if(num==1) {
            System.out.println("자바공부");
        }else if(num==2) {
            System.out.println("데이터베이스공부");
        }else if(num==3) {
            System.out.println("안드로이드공부");
        }else if(num==4) {
            System.out.println("기타 공부");
        }else {
            System.out.println("공부합시다.");
        }
        */
        switch(num) {
            case 1 :
                System.out.println("자바공부");break//break반드시 붙이기. 있는지 꼭 확인하기.
            case 2 :
                System.out.println("데이터베이스공부");break;
            case 3 :
                System.out.println("안드로이드공부");break;
            case 4 :
                System.out.println("기타공부");break;
            default :
                System.out.println("공부합시다.");
        }
    }
}
 
cs

 

  • 두 수를 입력하고 연산자에 따라 다른 결과값 출력하기 (Exam13)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package day01;
import java.util.Scanner;
public class Exam13 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("첫번째 수 입력>>");
        int a=sc.nextInt();
        System.out.println("두번째 수 입력>>");
        int b=sc.nextInt();
        System.out.println("연산자입력");
        String c=sc.next();
        
        switch(c) { //여기에는 쌍따옴표 안함. 변수 명만 적으면 됨.
            case "+" :
                System.out.println("덧셈결과: " +(a+b));break;
            case "-" :
                System.out.println("뺄셈결과: " +(a-b));break;
            case "*" :
                System.out.println("곱셈결과: " +(a*b));break;
            case "/" :
                System.out.println("나눗셈결과: " +(a/b));break;
            case "%" :
                System.out.println("나머지결과: " +(a%b));break;
            default :
                System.out.println("연산자가 틀렸습니다.");
        }
          if (c.equals("+")) { //문자열 값을 비교할때는 equals() 사용. 숫자 int는 ==임.
            System.out.println("덧셈결과: " +(a+b));
        }else if (c.equals("-")) {
            System.out.println("뺄셈결과: " +(a-b));
        }else if (c.equals("*")) {
            System.out.println("곱셈결과: " +(a*b));
        }else if (c.equals("/")) {
            System.out.println("나눗셈결과: " +(a/b));
        }else if (c.equals("%")) {
            System.out.println("나머지결과: " +(a%b));
        }else {
            System.out.println("연산자가 틀렸습니다.");
        }
        
        
    }
}
cs
  • 자료형 (int, long, float, double, char) (Exam03)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package day01;
public class Exam03 {
     public static void main (String[] args) {
          int a = 135;
          int b = 20;
          System.out.println("덧셈: " +(a+b));
          System.out.println("뺄셈: " +(a-b));
          System.out.println("곱셈: " +(a*b));
          System.out.println("나눗셈: " +(a/b));
          System.out.println("나머지: " +(a%b));
          System.out.println(a+"+"+b+"=" +(a+b));
          System.out.println(a+"%"+b+"=" +(a%b)); //문자열일때 "" 사이에.
          //int는 4바이트 (32비트)
          //long은 8바이트
          long c = 1000000000000L; //정수형은 int가 디폴트.
          
          float f = 3.25f; //4바이트
          double d = 3.25//8바이트. 부동 소수점은 더블이 디폴트임.
          
          //char는 문자 하나
          char ch = 'A';
          //char ch1 = "B"; 오류발생. 따옴표는 문자열을 표현.
    }
}

 

  • 자료형 (원의 넓이 구하기) (Exam04)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package day01;
public class Exam04 {
     public static void main(String[] args){
          double r = 5;
          final double PI = 3.14//final은 수정 못하도록 고정하는 거. final값은 보통 대문자로 표기.
          System.out.println(r*r*PI);
          
          float f = 5.0f; //4바이트
          int num = 10//4바이트
          f = num;
          //a=b 일때 a와 b는 같은 유형이어야 함. f와 num은 다른 데이터타입.
          //자바에선 정수형보다 부동소수점이 더 큰 형태
          //float = int 형변환 (캐스팅) <-자동형변환
          System.out.println("f:" +f);
          
          // num = f; float형을 작은 int형에 넣을 수는 없음.
     num = (int) f; //int <-float 형변환 (캐스팅) <-명시적형변환
        long num1 = 100L;
        
        f = num1; //float = long
        double area = r*r*PI;
        System.out.println("원넓이:" +area);
        
    }
}

 

  • if 문, 다중 if 문 (Exam05)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package day01;
public class Exam05 {
    public static void main(String[] args) {
        int a=49;
        //a는 50보다 크다
        if(a>50) { //true
            System.out.println("a는 50보다 크다");
//true일때 실행할 문장
        } else { //false
            System.out.println("a는 50보다 작다"); 
//false일때 실행할 문장
        }
        
        if(a%2==0) { //true라면 2로 나눴을때 나머지 0
            System.out.println(a+" : 짝수");
        } else { //false라면 2로 나눴을때 나머지가 1
            System.out.println(a+" : 홀수");
        }
//다중 if
        int b=252;
        if(b<0) {
            System.out.println("0미만");
        }else if(b<100) { //b가 0보다 작지 않다는 조건을 충족하지 않은 다음에 대조하는 조건. 
자동으로 b가 0과 100사이에 들어간다는 뜻임.
            System.out.println("0에서 99사이 수");
        }else if(b<200) {
            System.out.println("100에서 199사이 수");
        }else if(b<300) {
            System.out.println("200에서 299사이 수");
        }else {
            System.out.println("300 이상 수");
        }
int c=-100;
        if(c<0) {
            System.out.println("0미만");
        }
        if(c>=0 && c<100){
            System.out.println("0에서 99사이 수");
        }
        if(c>=100 && c<200) {
            System.out.println("100에서 200사이 수");
        }
        if(c>=300) {
            System.out.println("300이상 수");
        }
   int su=-142;
        if(su>=0 && su%2==0){
            System.out.println("su는 0보다 크고 짝수다");
        }
        else if(su>=0 && su%2!=0){
            System.out.println("su는 0보다 크고 홀수");
        }   
        else{
            System.out.println("su는 음수다");
        }
    }
}

 

 


 

2019-03 R | Eclipse Packages

438 MB 9,040 DOWNLOADS The Modeling package provides tools and runtimes for building model-based applications. You can use it to graphically design domain models, to leverage those models at design time by creating and editing dynamic instances, to collabo

www.eclipse.org


  • 변수 a 선언하고 숫자 5 값 주기, 홍길동 이름 출력
1
2
3
4
5
6
7
8
9
10
public class ExamTest01 {
    public static void main(String[] args){
        int a = 5;
        System.out.print("a= ");
        System.out.println(a);
        String name = "홍길동";
        System.out.print("name= ");
        System.out.println(name);
    }
}
 

 

  • 변수 num, num1과 그 합 구하기
1
2
3
4
5
6
7
8
9
10
11
12
public class NumTest {
    public static void main(String[] args){
        int num = 100;
        int num1 = 200;
        System.out.print("num = ");
        System.out.println(num);
        System.out.print("num1 = ");
        System.out.println(num1);
        System.out.print("num+num1 = ");
        System.out.println(num+num1);
    }
}

 

  • 나이와 이름 출력하기
1
2
3
4
5
6
7
8
package day01;
public class Exam02 {
       public static void main(String[] args) {
              int age = 100;
              String name = "홍길동";
              System.out.println(name +"의 나이는 " +age +"세입니다.");
       }
}
 

 

 

'Learning > JAVA' 카테고리의 다른 글

메인함수 클래스를 분리, 출력문 불러오기  (0) 2020.06.01
1차원 배열, 2차원 배열  (0) 2020.06.01
Switch문, for문, while문  (0) 2020.06.01
조건문, 값 입력하기  (0) 2020.06.01
자료형, if문, 다중 if문  (0) 2020.06.01

+ Recent posts