본문 바로가기

Learning/JAVA

메인함수 클래스와 출력 클래스 분리하고 출력하기

  • 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;
    }
}