• 자바의 다형성-상위 클래스를 통해 하위 클래스의 값을 다양한 형태로 돌려줌. 각 도형의 넓이의 합을 구할때. (Shape, ShapeMain, ShapeManager, Circle, Square)
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 day07;
import java.util.Scanner;
public class ShapeMain {
     static Scanner sc=new Scanner(System.in);
     
     public static void showMenu() {
          System.out.println("선택하세요...");
          System.out.println("1.원 2.사각형 3.보기 4.종료");
          System.out.print("선택:");
     }
     
     public static void main(String[] args) {
              ShapeManager sm=new ShapeManager();
              
              while(true) {
              ShapeMain.showMenu();
              //클래스 이름에 static 불였으니까 ShapeMain으로 부를 수 있음.
              int num=sc.nextInt();
              switch(num) {
              case 1 : //원입력
              case 2 : sm.inputData(num); break//사각형입력
              case 3 : sm.viewData(); break//전체보기
              case 4 : System.out.println("종료");
                         System.exit(0);
              default : 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
37
38
39
package day07;
public class ShapeManager {
     //입력받은 좌표, 반지름, 너비, 높이 등을 저장하기 위해 배열 선언
     //부모형으로 선언을 해야 Circle, Square 모두 적용가능
     Shape[]arr=new Shape[50];
     int cnt;
     
     public void inputData(int num) { //원->x,y,r 사각형->x,y,w,h
          System.out.println("도형입력....");
          System.out.print("x 좌표>>");
          int x=ShapeMain.sc.nextInt();
          System.out.print("y 좌표>>");
          int y=ShapeMain.sc.nextInt();
          
          if(num==1) { //원
              System.out.print("반지름>>");
              int r=ShapeMain.sc.nextInt();
              arr[cnt++]=new Circle(x,y,r);
          }
          else if(num==2) { //사각형
              System.out.print("너비>>");
              int w=ShapeMain.sc.nextInt();
              System.out.print("높이>>");
              int h=ShapeMain.sc.nextInt();
              arr[cnt++]=new Square(x,y,w,h);
          }
     }
     
     public void viewData() {
          double sum=0;
          for(Shape s: arr) {
              if(s==nullbreak;
              sum+=s.getArea();
              s.print();
          }
          System.out.println("전체 넓이: "+sum);
     }
     
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package day07;
public class Shape {
     private int x;
     private int y;
     
     public Shape(int x, int y) {
          this.x=x;
          this.y=y;
     }
     
     public void print() {
          System.out.println("좌표(x,y)=("+x+","+y+")");
     }
     
     public double getArea() {
          return 0.0;
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day07;
public class Circle extends Shape {
     private int r;
     final double PI=3.14;
     
     public Circle(int x, int y, int r) {
          super(x,y);
          this.r=r;
     }
     //오버라이딩
     public void print() {
          super.print();
          System.out.println("반지름: "+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
22
package day07;
public class Square extends Shape {
     private int w,h;
     
     public Square(int x, int y, int w, int h) {
          super(x,y);
          this.w=w;
          this.h=h;
     }
     //오버라이딩
     public void print() {
          super.print();
          System.out.println("너비: "+w);
          System.out.println("높이: "+h);
     }
     //오버라이딩
     public double getArea() { //리턴될 유형이 같아야 하므로 double로 맞춰줌.
          return w*h;
          //부모 getArea()에서 0.0을 리턴하긴 했지만 오버라이딩을 통해 w*h값을 돌려줌.
     }
     
}

 


  • 자바 Api중 toString은 Object이 가지는 메소드. toString()을 통해 오버라이딩하기. (ProductMain, Product, Buyer, TV, Computer, Audio)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package inheritance;
public class ProductMain {
     
     public static void main(String[] args) {
          Buyer b=new Buyer(1000); //바이어가 가진 돈
          TV tv=new TV(50); //tv의 가격
          Computer com=new Computer(100); //computer의 가격
          Audio audio=new Audio(70); //audio의 가격
          
          b.buy(tv); //tv와 com을 아우를 수 있는 자료형은 Product
          b.buy(com);
          b.showInfo();
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package inheritance;
public class TV extends Product {
     
     public TV(int price) {
          super(price);
     }
     //toString은 Object이 가지는 메소드이기 때문에 오버라이딩 할 수 있다.
     //오버라이딩을 함으로써 주소가 아니라 TV, Computer등 문자가 나오도록 함
     @Override
     public String toString() {
          return "TV";
     }    
}

 

 

1
2
3
4
5
6
7
8
9
10
11
package inheritance;
public class Computer extends Product {
     
     public Computer(int price) {
          super(price);
     }
     
     public String toString() {
          return "Computer";
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
package inheritance;
public class Audio extends Product {
     
     public Audio(int price) {
          super(price);
     }
     
     public String toString() {
          return "Audio";
     }
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package inheritance;
public class Product {
     protected int price;
     protected int bonusPoint;
     
     /* 생성자를 만들면 항상 부모의 생성자로 먼저 간다.
      * 부모의 생성자 Product에 인자가 있음.
      * 자식 클래스에 인자가 없는 생성자들이 있었음.
      * (Buyer클래스로 인해 하위 클래스가 인자가 있는 생성자로 바꾸면서 삭제)
      * 그러면 똑같이 인자가 없는 Product를 만들어줘야함.
     public Product() {
          
     }
     */
     public Product(int price) {
          this.price=price;
          bonusPoint=price/10;
     }    
}

 

 

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 inheritance;
public class Buyer {
     private int money;
     private int point;
     Product[] arr=new Product[10];
     int cnt;
     
     public Buyer(int money) { //생성자는 클래스 이름과 똑같이 만듦.
          this.money=money;
     }
     //구매하기
     public void buy(Product p) {
          arr[cnt++]=p;
          money-=p.price; //바이어가 가진 돈은 물건의 가격만큼 깎인다.
          point+=p.bonusPoint;
     }
     //구매내역
     public void showInfo() {
          for(int i=0;i<cnt;i++) {
              System.out.println("구매내역: "+arr[i]);
              //그냥 배열만 출력하면 주소값이 나옴.
          }
          System.out.println("잔액: "+money);
          System.out.println("포인트: "+point);
          
     }    
}

  • 객체 따로 선언하지 않고 클래스 형태를 매개변수로 적기, instanceof (AnimalTest1)
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 inheritance;
 
class Animal{
    public void move() {
        System.out.println("동물이 움직입니다.");
    }
}
 
class Human extends Animal {
    public void move() {
        System.out.println("사람이 두 발로 걷습니다.");
    }
}
 
class Tiger extends Animal {
    public void move() {
        System.out.println("호랑이가 네 발로 뜁니다.");
    }
}
 
class Eagle extends Animal {
    public void move() {
        System.out.println("독수리가 하늘을 납니다.");
    }
}
 
public class AnimalTest1 {
    public static void main(String[] args) {
        AnimalTest1 aTest=new AnimalTest1();
        aTest.moveAnimal(new Human()); 
        aTest.moveAnimal(new Tiger()); //한번만 쓰고 더이상 안만들 것은 객체를 따로 선언하지 않고 new Tiger()이런 식으로 매개변수로 적어줌
        aTest.moveAnimal(new Eagle());
        
        Human h=new Human();
        if(h instanceof Animal) { //instanceof는 이 객체가 어느 소속인지 물어보는 키워드. Human보다 Animal이 상위 개념이므로 맞다라고 출력. 
            System.out.println("맞다");
        }else {
            System.out.println("틀리다");
        }
        
        Animal a=new Animal();
        if(a instanceof Human) { //a는 Animal. Human보다 큰 개념이므로 틀리다11가 출력.
            System.out.println("맞다11");
        }else {
            System.out.println("틀리다11");
        }
        
    }
    
    public void moveAnimal(Animal animal) { //Animal에서 상속받은 클래스가 매개변수로 넘어오면 모두 Animal형으로 변환됨. animal에 휴먼, 타이거, 이글 등..올수 있음.
        animal.move();
    }
}
 

 


  • 추상클래스-abstract (AbsShape, AbsShapeMain, AbsCircle, AbsSquare)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package day07;
public class AbsShapeMain {
     public static void main(String[] args) {
          AbsCircle ac=new AbsCircle();
          ac.draw();
          ac.move();
          
          AbsSquare as=new AbsSquare();
          as.draw();
          as.move();
          as.print();
          
          //AbsShape ah=new AbsShape(); //추상이라서 안된다. 
          //추상클래스엔 객체를 생성할 수 없다. 하위클래스에서 반드시 추상클래스의 추상 메소드 구현.
          AbsShape ah=new AbsCircle(); //이런식으로 접근한다.
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package day07;
public abstract class AbsShape {
     /*
      *그리다. 원을 그리면 원을 그리다. 사각형을 그리면 사각형을 그리다.
      *자식 클래스들에 따라 구현되도록.
      *그러려면 추상 메소드를 만들어놓고 클래스도 추상클래스로 변하게.
      */
     public abstract void draw();
     //이동하다
     public abstract void move();
     
     public void print() {
          System.out.println("도형그리다");
     }
     
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package day07;
public class AbsCircle extends AbsShape {
     @Override
     public void draw() {
          // TODO Auto-generated method stub
          System.out.println("원 그리기");
     }
     @Override
     public void move() {
          // TODO Auto-generated method stub
          System.out.println("원 이동하기");
     }
}

 

 

1
2
3
4
5
6
7
8
9
package day07;
public class AbsSquare extends AbsShape {
     public void draw() { //반드시 선언해줘야함. 부모 클래스인 AbsShape은 추상클래스이기 때문에 그 안에 있는 추상메소드를 구현하도록 해야함.
          System.out.println("사각형 그리기");
     }
     public void move() {
          System.out.println("사각형 이동하기");
     }
}

 


  • 추상클래스 (Player, PlayerLevel, BeginnerLevel, AdvancedLevel, SuperLevel, MainBoard)
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 inheritance;
public class Player {
     private PlayerLevel level; //PlayerLevel이 가지는 level변수 선언
     
     public Player() {
          level=new BeginnerLevel();
          level.showLevelMessage();
     }
     
     public PlayerLevel getLevel() {
          return level;
     }
     
     public void upgradeLevel(PlayerLevel level) { //매개변수 자료형은 모든 레벨로 변환 가능한 PlayerLevel
          this.level=level; //현재 자신의 level을 매개변수로 받은 level로 변경하고 레벨 메시지 출력
          level.showLevelMessage();
     }
     
     public void play(int count) { //PlayerLevel의 템플릿 메서드 go()호출
          level.go(count);
     }
     
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package inheritance;
public abstract class PlayerLevel {
     public abstract void run();
     public abstract void jump();
     public abstract void turn();
     public abstract void showLevelMessage();
     
     final public void go(int count) {
          run();
          for(int i=0;i<count;i++) {
              jump();
          }
          turn();
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package inheritance;
public class BeginnerLevel extends PlayerLevel {
     @Override
     public void run() {
          System.out.println("천천히 달립니다.");
     }
     @Override
     public void jump() {
          System.out.println("Jump할 줄 모르지롱.");
     }
     @Override
     public void turn() {
          System.out.println("Turn할 줄 모르지롱.");
     }
     @Override
     public void showLevelMessage() {
          System.out.println("******초보자 레벨입니다.******");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package inheritance;
public class AdvancedLevel extends PlayerLevel{
     @Override
     public void run() {
          System.out.println("빨리 달립니다.");
     }
     @Override
     public void jump() {
          System.out.println("높이 Jump합니다.");
     }
     @Override
     public void turn() {
          System.out.println("Turn할 줄 모르지롱.");
     }
     @Override
     public void showLevelMessage() {
          System.out.println("******중급자 레벨입니다.******");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package inheritance;
public class SuperLevel extends PlayerLevel{
     @Override
     public void run() {
          System.out.println("엄청 빨리 달립니다.");
     }
     @Override
     public void jump() {
          System.out.println("아주 높이 Jump합니다.");
     }
     @Override
     public void turn() {
          System.out.println("한 바퀴 돕니다.");
     }
     @Override
     public void showLevelMessage() {
          System.out.println("******고급자 레벨입니다.******");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package inheritance;
public class MainBoard {
     public static void main(String[] args) {
          Player player=new Player(); //처음 생성하면 BeginnerLevel
          player.play(1);
          
          AdvancedLevel aLevel=new AdvancedLevel();
          player.upgradeLevel(aLevel);
          player.play(2);
          
          SuperLevel sLevel=new SuperLevel();
          player.upgradeLevel(sLevel);
          player.play(3);
     }
}

 


  • 전부다 추상인걸로 이뤄진 것을 interface라 하고 extends가 아닌 implements를 사용. 추상과 마찬가지로 new라는 키워드로 생성불가능하지만 추상과 달리 여러개를 상속받을 수 있다. 자바의 불가능한 다중 상속을 가능하게 만들기 위해 extends와 implements를 함께 쓴다. (InterExam)
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 inheritance;
interface InterTest{
     public void test();
}
//전부다 추상이라면 추상클래스라 안붙이고 interface를 붙인다.
interface InterShape{
     public void draw();
     public void move();
     public void print();
}
//interface는 extends가 아닌 implements를 사용.
class InterCircle implements InterShape, InterTest{
     //하위 클래스가 상위 추상 클래스의 메소드를 부를때는 구현(중괄호 {})해야함.꼭.
     //InterTest도 상속받았기 때문에 test(){}도 구현.
     public void draw() {}
     public void move() {}
     public void print() {}
     public void test() {}
}
class Inter {
     public void interTest() {
     }
}
//자바는 다중 상속이 안되게끔 되어있는데 다중 상속을 받아야할때는 이렇게 표현.
//상속을 받고 interface를 써줌.
class InterRectangle extends Inter implements InterShape,
InterTest{
     public void draw() {}
     public void move() {}
     public void print() {}
     public void test() {}
}
public class InterExam {
}

 


  • interface-implements로 원 넓이, 둘레, 사각형 넓이, 둘레 구하기 (InterfaceMain, Shape)
1
2
3
4
5
6
7
8
9
10
11
12
13
package interfaceTest;
public class InterfaceMain {
     
     public static void main(String[] args) {
          //앞에가 Rectangle, Circle형이 아니다. 부모클래스란 소리.
          Shape rec=new Rectangle(5,7);
          Shape circle=new Circle(5);
          System.out.println("원 넓이: "+circle.area());
          System.out.println("원 둘레: "+circle.circum());
          System.out.println("사각형 넓이: "+rec.area());
          System.out.println("사각형 둘레: "+rec.circum());
     }
}

 

 

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
package interfaceTest;
public interface Shape {
     double area(); //넓이
     double circum(); //둘레 
}
class Rectangle implements Shape{
     private int w, h;
     public Rectangle(int w, int h) {
          this.w=w;
          this.h=h;
     }
     public double area() {
          return w*h;
     }
     public double circum() {
          return (w+h)*2;
     }
}
class Circle implements Shape{
     private int r;
     public Circle (int r) {
          this.r=r;
     }
     public double area() {
          //Math는 수학적 계산이 완료된 클래스.
          //멤버변수로 PI가 그 중 하나.
          return r*r*Math.PI;
     }
     public double circum() {
          return 2*r*Math.PI;
     }
}

  • 원화를 달러로 변환, 키로미터를 마일로 변환하는 두 클래스는 상위의 추상클래스를 상속받는다. (ConverterMain, Converter, Won2Dollar, Km2Mile)
1
2
3
4
5
6
7
8
9
10
11
package interfaceTest;
public class ConverterMain {
     public static void main(String[] args) {
          //원화를 달러로
          Won2Dollar toDollar=new Won2Dollar(1200);
          toDollar.run();
          //km를 마일로
          Km2Mile toMile=new Km2Mile(1.6);
          toMile.run();
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package interfaceTest;
import java.util.Scanner;
//추상인 메소드, 추상아닌 메소드가 섞여 있으므로 추상 클래스로 만든다. (모두 추상이면 interface)
public abstract class Converter {
     abstract protected double convert(double src);
     abstract String srcString();
     abstract String destString();
     protected double ratio;
          
     Scanner scanner=new Scanner(System.in);
     public void run() { //교환
          //srcString, destString은 돈이 들어갈 수도, 길이 단위가 들어갈 수도 있다.
          //따라서 현재 Convert 클래스로는 정의하지 못하고
          //하위 클래스들이 정의를 해야하므로 추상메소드로 바꾸고 따라서 클래스도 추상으로 바꿔야한다.
          System.out.println(srcString()+"을 "+destString()+"로 바꿉니다.");
          System.out.print(srcString()+"을 입력하세요>>");
          double val=scanner.nextDouble();
          double res=convert(val); //스캐너가 입력한 값을 인수로 받는다.
          System.out.println("변환 결과: "+res+destString()+"입니다.");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package interfaceTest;
public class Won2Dollar extends Converter {
     public Won2Dollar(int don) {
          super.ratio=don;
     }
     @Override
     protected double convert(double src) {
          //src/don이라고 하면 don이 뭔지 모르니까 부모클래스에 ratio를 주고 그걸 나누는 것
          return src/ratio;
     }
     @Override
     String srcString() {
          return "원";
     }
     @Override
     String destString() {
          return "달러";
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package interfaceTest;
public class Km2Mile extends Converter {
     public Km2Mile (double ratio) {
          super.ratio=ratio;
     }
     @Override
     protected double convert(double src) {
          // TODO Auto-generated method stub
          return src/ratio;
     }
     @Override
     String srcString() {
          // TODO Auto-generated method stub
          return "Km";
     }
     @Override
     String destString() {
          // TODO Auto-generated method stub
          return "mile";
     }
}

 


  • ArrayList를 사용하여 배열 선언하기. ArrayList에는 객체가 들어가며 추가할때는 add, 제거할때는 remove명령어 사용 (ArrayTest)

 

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
package utilTest;
import java.util.ArrayList;
public class ArrayTest {
     public static void main(String[] args) {
          ArrayList arr=new ArrayList(); //ArrayList엔 객체가 들어간다. 메소드로 접근
          arr.add(1); //ArrayList에 추가하는 명령어는 add
          arr.add("안녕");
          arr.add(3.2); //Double이라는 클래스가 들어감. Wrapper 클래스로 변환되었기 때문에 추가가되는 것.
          System.out.println("마지막: " +arr.get(arr.size()-1)); //인덱스에 접근하는 메소드는 get()
          System.out.println(arr.size()); //length가 아니라 size를 사용
          arr.add(new Integer(3)); //add는 맨 끝에 붙임.
          System.out.println("크기: "+arr.size());
          System.out.println("마지막: " +arr.get(arr.size()-1));
          arr.remove(1); //안녕이 지워짐.
          arr.remove("안녕"); //안녕이 지워져있기 때문에 또 지울 수 없음.
          System.out.println("크기: "+arr.size());
          arr.add(1,"지금 자바");
          System.out.println("크기: "+arr.size());
          //ArrayList의 list엔 String형만 넣겠다. 제네릭 표시. 특정 개체로 유형을 정함.
          //클래스에 객체 오브젝이 들어감. int는 기본 자료형이기 때문에 정수만 받고 싶다면 Integer라고 적어야함.
          ArrayList<Integer>list=new ArrayList<Integer>();
          list.add(1);
          list.add(2);
          ArrayList<String>alist=new ArrayList<String>();
          alist.add("자바");
          alist.add("Java");
          for(int i=0;i<alist.size();i++) {
              System.out.println(alist.get(i));
          }
          for(String s:alist) {
              System.out.print(s+"\t");
          }
          System.out.println();
          for(int i:list) { //컴파일러가 알아서 wrapper해줘서 int를 사용할 수 있다.
              System.out.print(i+"\t");
          }
     }
}
cs

 


+이전의 ShapeManager와 Buyer 클래스에 배열을 ArrayList형식으로 바꾼다면..

 

<ShapeManager>

Shape[]arr=new Shape[50]; 

->ArrayList <Shape> slist=new ArrayList <Shape>();

 

arr[cnt++]=new Circle(x,y,r);

->slist.add(new Circle(x,y,r));

 

arr[cnt++]=new Square(x,y,w,h);

->slist.add(new Square(x,y,w,h));

 

for(Shape s: slist){

    sum+=s.getArea();

    s.print();
}


<Buyer>

Product[] arr=new Product[10];

->ArrayList <Product>list=new ArrayList<Product>();

 

arr[cnt++]=p;

->list.add(p);

 

for(int i=0;i<cnt;i++) {

->for(int i=0;i<list.size();i++) {

 

System.out.println("구매내역: "+arr[i]);

->System.out.println("구매내역: "+list.get(i)); 
System.out.println("가격: "+list.get(i).price);

  • 이차원배열의 인덱스 값을 일차원배열로 지정, 출력 순서를 행 단위로 바꾸기 (ShiftArray)
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
package day06_objectArray;
public class ShiftArray {
     
     public static void shiftArray(int [][]arr) {
          //일차원 배열을 만들고 그 배열에 arr의 마지막 행 값을 넣는다.
          int []tmp=arr[arr.length-1];
          //arr의 인덱스가 2에 1의 값을 넣는다.
          //arr의 인덱스가 1에 0의 값을 넣는다.       
          for(int i=arr.length-2;i>=0;i--) {
                   arr[i+1]=arr[i];
              }
          //arr의 인덱스가 0의 위치에 처음 만든 일차원 배열을 넣는다.
          arr[0]=tmp;
     }
     
     public static void showArray(int [][]arr) {
          for(int i=0;i<arr.length;i++) {
              for(int j=0;j<arr[i].length;j++) {
                   System.out.print(arr[i][j]+"\t");
              }System.out.println();
          }
     }
     
     
     public static void main(String[] args) {
          int [][]arr= {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
          
          System.out.println("1차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          System.out.println("2차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          /*
           * 1차 shift...
           * 7 8 9
           * 1 2 3
           * 4 5 6
           * 2차 shift...
           * 4 5 6
           * 7 8 9
          */
     }
}

 


  • ArrayList활용. 학생의 학번, 이름, 과목 성적 입력하고 출력하기 (StudentTest, Student, Subject)
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 day06_objectArray.arraylist;
//import java.util.ArrayList;
public class Student {
     int studentID;
     String studentName;
     Subject []subjectList;
     int index;
     //ArrayList<Subject>subjectList;
     
     public Student(int studentID, String studentName) {
          this.studentID=studentID;
          this.studentName=studentName;
          subjectList=new Subject[10];
          //subjectList=new ArrayList<Subject>();
     }
     //배열을 대신해서 사용할 수 있는게 ArrayList.
     //학생이 여러 과목을 듣는데 그걸 따로 과목에 대한 클래스로 따로 분류
     //그걸 배열에 담음.
     //배열은 처음에 공간을 정해줘야함. 대신에 ArrayList는 추가한만큼 크기가 변화함
     //ArrayList는 함수를 이용해서 접근.
     
     public void addSubject(String name, int score) {
          Subject subject=new Subject();
          subject.setName(name);
          subject.setScorePoint(score);
          subjectList[index++]=subject;
          //subjectList.add(subject);
     }
     
     public void showStudentInfo() {
          int total=0;
          for(Subject s : subjectList) {
              if(s==nullbreak;
              total+=s.getScorePoint();
              System.out.println("학생 "+studentName+"의 "+s.getName()+"과목 성적은 "+s.getScorePoint()+"입니다.");
          }
          System.out.println("학생 "+studentName+"의 총점은 "+total+" 입니다.");
     }
}

 


  • 학생클래스, 버스, 지하철, 택시 클래스를 구현하여 학생이 버스나 지하철을 타고 요금을 냈을때 학생이름, 잔액, 버스 승객, 버스 수입, 지하철 승객, 지하철 수입을 출력하기 (Student, Bus, Subway, Taxi, TakeTrans)
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 cooperation;
 
public class TakeTrans {
    
    public static void main(String[] args) {
        Student s1=new Student("홍길동"5000);
        Student s2=new Student("이순신"10000);
        Student s3=new Student("Edward"20000);
        
        Bus bus=new Bus(100); //100번 버스
        //s1학생이 100번 버스를 탄다.
        s1.takeBus(bus); //매개변수가 객체가 됨.
        
        Subway subway=new Subway("2호선");
        //s2학생이 2호선 지하철을 딴다.
        s2.takeSubway(subway);
        
        Taxi taxi=new Taxi("yellow");
        s3.takeTaxi(taxi);
        
        s1.showInfo();
        s2.showInfo();
        s3.showInfo();
        
        bus.showInfo();
        subway.showInfo();
        taxi.showInfo();
        
    }
}

 

 

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 cooperation;
 
public class Student { 
    private String studentName; //학생이름
    private int grade; //학년
    private int money; //학생이 가지고 있는 돈
    
    public Student(String studentName, int money) {
        this.studentName=studentName;
        this.money=money;
    }
    
    //버스타다
    public void takeBus(Bus bus) { //Bus형에 bus가 들어감. 매개변수를 객체로.
        bus.take(1000);
        this.money-=1000;
    }
    
    //지하철타다
    public void takeSubway(Subway subway) { //Subway형에 subway가 들어감.
        subway.take(1500);
        this.money-=1500;
    }
    
    public void takeTaxi(Taxi taxi) {
        taxi.take(10000);
        this.money-=10000;
    }
    
    public void showInfo() {
        System.out.println("학생 이름: "+studentName);
        System.out.println("학생 잔액: "+money);
    }
    
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package cooperation;
 
public class Subway {
    private String subwayNumber; //지하철번호
    private int passengerCount; //승객수
    private int money; //수입
    
    public Subway (String subwayNumber) {
        this.subwayNumber=subwayNumber;
    }
    
    //승객이 돈을 내고 탑승
    public void take(int money) {
        this.money+=money; //수입증가
        passengerCount++//승객 수 증가
    }
    
    public void showInfo() {
        System.out.println("지하철 "+subwayNumber);
        System.out.println("승객 "+passengerCount);
        System.out.println("수입 "+money);
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package cooperation;
 
public class Taxi {
    private String taxiColor;
    private int money;
    private int passengerCount;
    
    public Taxi(String taxiColor) {
        this.taxiColor=taxiColor;
    }
    
    public void take(int money) {
        this.money+=money;
        passengerCount++;
    }
    
    public void showInfo() {
        System.out.println("택시 "+taxiColor);
        System.out.println("승객 "+passengerCount);
        System.out.println("수입 "+money);
    }    
}

 


  • 자바의 상속성 (Child, Father, GrandFather, Main)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package day07;
public class Main {
     public static void main(String[] args) {
          Father f1=new Father();
//        f1.fatherPrint();
          
          Child c1=new Child();
//        c1.childPrint();
          
//        f1.methodTest();
          //c1.test();
//        c1.methodTest();
          GrandFather g1=new GrandFather();
          c1.grandPrint();
          f1.grandPrint();
          
     }    
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package day07;
public class Child extends Father { //Child는 Father걸 다 쓸 수 있다. 상속받는다.
     //이미 만들어져 있는걸 갖다 쓸 수 있기 때문에 중복을 최소화 할 수 있다. 코드가 간략해짐.
     //상속 받았기 때문에 무조건 생성자를 먼저 수행하고 자신의 메소드를 수행
     //자바에서 다중상속은 안되고 단일상속만 된다.
     public Child() {
//        super("부모를 호출"); //super();는 부모의 생성자를 부르는 말. 생략 가능하다.
          //super(인자);
          System.out.println("자식 생성자");
     }
     
     public void childPrint() {
          System.out.println(super.str); //this가 자기 자신의 객체를 불렀던 것처럼, 괄호 없는 super는 부모의 객체를 부른다.
          System.out.println("child print 메소드");
     }
     
     public void test() {
          System.out.println("test method");
     }
}

 

 

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 day07;
public class Father extends GrandFather {
     String str="아버지"//멤버변수
     
     public Father() {
          System.out.println(str+" 생성자 ");
     }
     
     public Father(String msg) {
          System.out.println(msg);
     }
     
     public void fatherPrint() {
          System.out.println("father print 메소드");
     }
     
     public void methodTest() {
          System.out.println("test method");
     }
     
     //오버라이드. (메소드 오버라이딩) 상속관계에 있어서 부모의 것을 자식이 재정의 하는 것.
     //(오버로딩: 메소드나 생성자 이름은 같은데 괄호안에 들어있는 매개변수가 달라서 다르게 접근하는 것)
     public void grandPrint() { //할아버지 메소드. 오버라이딩 됨. 할아버지가 아니라 아버지에 있는 것이 출력됨.
          System.out.println("할아버지 grandPrint 메소드를 father가 수정함");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
package day07;
public class GrandFather {
     String name="할아버지";
     //생성자
     public GrandFather() {
          System.out.println(name+" 생성자");
     }
     
     public void grandPrint() {
          System.out.println("grandPrint 메소드");
     }
}

 


  • 자바의 상속성-부모의 생성자를 못찾을때 디폴트 생성자 만들어주기, 부모의 인자를 부를때 super 사용. (PointMain, Point)
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 day07;
public class PointMain extends Point {
     private String color;
     public PointMain (int x, int y, String color) {
          super(x,y); //x,y가 있는 부모의 생성자를 불러준다.
          this.color=color;
     }
     //색깔도 출력시키고 싶다면 좌표만 출력시키는 부모의 disp()메소드를 오버라이딩 해주면 된다.
     //부모의 인자값 출력하려면 super를 붙이면 됨.
     @Override //어노테이션. 컴파일 할때 알려줌. 이름이 달라지면 오류발생. 오버라이드가 아니게 되므로.
     public void disp() {
          // TODO Auto-generated method stub
          super.disp();
          System.out.println("Color: "+color);
     }
     public static void main(String[] args) {
          PointMain pm=new PointMain(5,5,"Yellow");
          pm.disp();
          pm.move(10,20);
          pm.disp();    
          
          System.out.println(pm.str);
          
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package day07;
public class Point {
     private int x;
     private int y;
     protected String str="Point"//protected는 상속관계의 접근제어자.
     
     //인자없는 생성자를 만들어준 것. 껍데기
     Point(){}
     
     public Point(int x, int y) {
          this.x=x;
          this.y=y;
     }
     
     public void disp() {
          System.out.println("점(x,y)=("+x+","+y+")");
     }
     
     public void move(int x, int y) {
          this.x=x;
          this.y=y;
     }
}

 


  • 자바의 상속성-오버라이드를 통해 TV의 스펙 출력하기 (TVMain, TV, ColorTV, IPTV)
1
2
3
4
5
6
7
8
9
10
11
12
package day07;
//32인치 1024컬러
//나의 IPTV는 192.1.1.2 주소의 32인치 2048컬러
public class TVMain {
     public static void main(String[] args) {
          ColorTV myTV=new ColorTV(32,1024);
          myTV.printProperty();
          
          IPTV iptv=new IPTV("192.1.1.2",32,2048);
          iptv.printProperty();
     }
}

 

 

1
2
3
4
5
6
7
package day07;
public class TV {
     protected int inch;
     public TV(int inch) {
          this.inch=inch;
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
package day07;
public class ColorTV extends TV {
     protected int nColors;
     
     public ColorTV(int inch, int nColors) {
          super(inch);
          this.nColors=nColors;
     }
     
     public void printProperty() {
          System.out.println(inch+"인치 "+nColors+"컬러");
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package day07;
public class IPTV extends ColorTV {
     private String address;
     
     public IPTV(String address, int inch, int nColors) {
          super(inch,nColors); //super로 가져오는 인자들은 항상 맨 윗줄에 써야함.
          this.address=address;
     }
     
     public void printProperty() {
          System.out.println("나의 IPTV는 "+this.address+" 주소의 "+inch+"인치 "+nColors+"컬러");
          super.printProperty();
     }
}

 


  • 자바의 상속성-메뉴 입력하여 원, 사각형 등의 도형 스펙 출력하기 (ShapeMain, Shape, Circle, Square, ShapeManager)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package day07;
 
public class Shape {
    private int x;
    private int y;
    
    public Shape(int x, int y) {
        this.x=x;
        this.y=y;
    }
    
    public void print() {
        System.out.println("좌표(x,y)=("+x+","+y+")");
    }
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package day07;
 
public class Circle extends Shape {
    private int r;
    
    public Circle(int x, int y, int r) {
        super(x,y);
        this.r=r;
    }
    //오버라이딩
    public void print() {
        super.print();
        System.out.println("반지름: "+r);
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
package day07;
 
public class Square extends Shape {
    private int w,h;
    
    public Square(int x, int y, int w, int h) {
        super(x,y);
        this.w=w;
        this.h=h;
    }
    
    public void print() {
        super.print();
        System.out.println("너비: "+w);
        System.out.println("높이: "+h);
    }
}

 

 

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
package day07;
 
import java.util.Scanner;
 
public class ShapeMain {
    static Scanner sc=new Scanner(System.in);
    
    public static void showMenu() {
        System.out.println("선택하세요...");
        System.out.println("1.원 2.사각형 3.보기 4.종료");
        System.out.print("선택:");
    }
    
    public static void main(String[] args) {
            ShapeManager sm=new ShapeManager();
            
            while(true) {
            ShapeMain.showMenu(); 
            //클래스 이름에 static 불였으니까 ShapeMain으로 부를 수 있음.
            int num=sc.nextInt();
            switch(num) {
            case 1 : //원입력
            case 2 : sm.inputData(num); break//사각형입력
            case 3 : sm.viewData(); break//전체보기
            case 4 : System.out.println("종료");
                     System.exit(0);
            default : 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 day07;
 
public class ShapeManager {
    //입력받은 좌표, 반지름, 너비, 높이 등을 저장하기 위해 배열 선언
    //부모형으로 선언을 해야 Circle, Square 모두 적용가능
    Shape[]arr=new Shape[50]; 
    int cnt;
    
    public void inputData(int num) { //원->x,y,r 사각형->x,y,w,h
        System.out.println("도형입력....");
        System.out.print("x 좌표>>");
        int x=ShapeMain.sc.nextInt();
        System.out.print("y 좌표>>");
        int y=ShapeMain.sc.nextInt();
        
        if(num==1) { //원
            System.out.print("반지름>>");
            int r=ShapeMain.sc.nextInt();
            arr[cnt++]=new Circle(x,y,r);
        }
        else if(num==2) { //사각형
            System.out.print("너비>>");
            int w=ShapeMain.sc.nextInt();
            System.out.print("높이>>");
            int h=ShapeMain.sc.nextInt();
            arr[cnt++]=new Square(x,y,w,h);
        }
    }
    
    public void viewData() {
        for(Shape s: arr) {
            if(s==nullbreak;
            s.print();
        }
    }
}

 

  • 과일의 가격, 할인율, 할인율에 따른 과일가격 변동 출력 (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는 음수다");
        }
    }
}

 

 

+ Recent posts