190426_Day15 복습, 이벤트 처리

복습

class Child
{
    Child()
    {
        My m = new My();
        m.goodChoice( this );
    }
    public void hello()
    {
        System.out.print("hi");
    }
    public static void main(String[] args)
    {
        Child c = new Child();
    }
}
Class My
{
    void goodChoice(Child c)
    {
        Child c = new Child();
        c.hello();
    }
}
  • <이벤트처리>

    • 사건이 발생했을 때 기능을 부여하는 것

    • 컴포넌트에서 사건(버튼, 스크롤바, 체크박스, 마우스 움직임) 발생시 기능 부여하는것

    • 이벤트 처리는 어떻게? 내가 기능부여할 컴포넌트 선정!

    class My
    {
        Frame f;
        Button bt_hello, bt_exit;
        Checkbox cb_apple;
    }
    • bt_hello, bt_exit list

    • 자료형은 Button, List 컴포넌트

    • API 문서 찾기 (각 클래스내에서 메소드 add Listener 찾기)

    • Button : addActionListener(ActionListener l)

    • List : addItemListener(ItemListener l)

    • 인터페이스 상속!!

    • 인터페이스 내의 선언된 메소드를 My클래스에서 구현(오버라이딩)

    • class My implements ActionListener, ItemListener
      {
        //implements 구현의 약속
        public void actionPerformed(ActionEvent e)
        {
      
        }
      }
    • -
package j0426;

import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

public class WindowCloseTest extends Frame implements WindowListener
{
    public WindowCloseTest()
    {
        setTitle("창닫기 테스트");
        setSize(300,300);
        setVisible(true);

        addWindowListener(this);
    }//생성자

    //우리는 얘만 필요해!
    public void windowClosing(WindowEvent e)
    {
        System.out.println( "X버튼 클릭" );
        //프로그램 종료 => System.exit(정수); 정수:0 양수[정상] 또는 음수[비정상종료]
//      System.exit(0);
    }

    public void windowOpened(WindowEvent e){}
    public void windowClosed(WindowEvent e){}
    public void windowIconified(WindowEvent e){}
    public void windowDeiconified(WindowEvent e){}
    public void windowActivated(WindowEvent e){}
    public void windowDeactivated(WindowEvent e){}

    public static void main(String[] args)
    {
        new WindowCloseTest();
    }
}
package j0426;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class WindowCloseTest2 extends WindowAdapter
{
    Frame f; // extends 저걸 했으니 Frame 이렇게 해줘야 함

    public WindowCloseTest2()
    {
        f = new Frame("창닫기 테스트2");
        f.setSize(300,500);
        f.setVisible(true);

        f.addWindowListener(this); // f : 이벤트소스, windowClosing() : 이벤트 핸들러
    }

    @Override
    public void windowClosing(WindowEvent e)
    {
        System.out.println("프레임 창 닫기");
        System.exit(0);
    }

    public static void main(String[] args)
    {
        new WindowCloseTest2();
    }
}
package com.encore.j0426;

import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import com.encore.j0425.ButtonEventTest;

//프레임창 우측상단의 X버튼 구현
public class WindowCloseTest3 extends Frame {


   public WindowCloseTest3() {
      setTitle("창닫기테스트3"); 

      setSize(300,300);
      setVisible(true);

      //My m = new My();
      //addWindowListener(m);//프레임과 밑에 추가된 핸들러를 연결!!

      //addWindowListener(new My());


      //익명의 내부클래스(Anonymous InnerClass)
      /*
       addWindowListener(             
               //extends WindowAdapter
                new WindowAdapter()
               {//클래스 시작

                    @Override
                    public void windowClosing(WindowEvent e) {
                      System.out.println("X버튼클릭(세번째)~!!");
                      System.exit(0);
                    }
                }//클래스 끝
        );
       */
       addWindowListener(new WindowAdapter() {//익명의 내부클래스 시작!!
           @Override
           public void windowClosing(WindowEvent e) {
             System.out.println("쉬었다 합시다~!!^^");  
             System.exit(0);
           }
       });

   }//생성자




   public static void main(String[] args) {
      new WindowCloseTest3();//프레임 객체 생성
   }

}
package j0426;


import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;


//프레임창 우측상단의 X버튼 구현
public class WindowCloseTest3 extends Frame {


   public WindowCloseTest3() {
      setTitle("창닫기테스트3"); 

      setSize(300,300);
      setVisible(true);

      //My m = new My();
      //addWindowListener(m);//프레임과 밑에 추가된 핸들러를 연결!!

      //addWindowListener(new My());


      //익명의 내부클래스(Anonymous InnerClass)
      /*
       addWindowListener(             
               //extends WindowAdapter
                new WindowAdapter()
               {//클래스 시작

                    @Override
                    public void windowClosing(WindowEvent e) {
                      System.out.println("X버튼클릭(세번째)~!!");
                      System.exit(0);
                    }
                }//클래스 끝
        );
       */
       addWindowListener(new WindowAdapter() {//익명의 내부클래스 시작!!
           @Override
           public void windowClosing(WindowEvent e) {
//           System.out.println("쉬었다 합시다~!!^^");  
//           System.exit(0);
              //현재 프레임의 타이틀을 '불타는 금요일'로 변경하시오
               setTitle("불타는 금요일");

           }
       });

   }//생성자




   public static void main(String[] args) {
      new WindowCloseTest3();//프레임 객체 생성
   }

}
package j0426;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//CardLayout테스트( 컴포넌트를 같은 위치에 부착)
public class CardTest implements ActionListener{
   Frame f;

   Panel redp, bluep, yellowp;//색깔패널
   Button bt1,bt2,bt3;//다음 버튼

   Panel card1,card2,card3;//카드

   CardLayout card;

   public CardTest() {
      f = new Frame("카드레이아웃");

      redp = new Panel();
       redp.setBackground(Color.RED);
      bluep = new Panel();
       bluep.setBackground(Color.BLUE);
      yellowp = new Panel();
       yellowp.setBackground(Color.YELLOW);

      bt1 = new Button("다음"); //301호
      bt2 = new Button("다음"); //302호
      bt3 = new Button("다음"); //303호

      card1 = new Panel();
        card1.setLayout(new BorderLayout(0, 10));
        card1.add("Center",redp);
        card1.add("South",bt1);

      card2 = new Panel();
        card2.setLayout(new BorderLayout(0, 10));
        card2.add("Center",bluep);
        card2.add("South",bt2);

      card3 = new Panel();
        card3.setLayout(new BorderLayout(0, 10));
        card3.add("Center",yellowp);
        card3.add("South",bt3);

      card =  new CardLayout();
      f.setLayout(card);
        f.add(card1,"first");//처음에 보이는 카드!!
        f.add(card2,"second");
        f.add(card3,"third");
      //f.add(붙일 컴포넌트, 별명);   alias별명

      //card.show (Container parent, String name);  
      // 를    보여라                 어디에                  무엇을(별명)
      card.show(f, "third");

      f.setSize(250,300);  
      f.setVisible(true);

      f.addWindowListener(new WindowAdapter() {
           @Override
           public void windowClosing(WindowEvent e) {
              System.exit(0);
           }
       });

      bt1.addActionListener(this);
      bt2.addActionListener(this);
      bt3.addActionListener(this);

   }//생성자

   @Override
   public void actionPerformed(ActionEvent e) {//이벤트 핸들러
      Object ob = e.getSource();//이벤트 소스의 주소(bt1 또는 bt2 또는 bt3의 주소)  
      //ob=301호 

      //첫번째버튼 눌렀을때 - 두번째 카드보이기
      if(ob == bt1) 
       card.show(f,"second");
      //두번째버튼 눌렀을때 - 세번째 카드보이기
      else if(ob == bt2)
       card.show(f,"third");
      //세번째버튼 눌렀을때 - 첫번째 카드보이기
      else //if(ob == bt3)
       card.show(f,"first");
   }
   public static void main(String[] args) {
       new CardTest();
   }

}
package j0426;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class HelloEventTest extends Frame implements ActionListener
{

    Button bt_hello, bt_clear, bt_exit;
    Checkbox cb1, cb2, cb3;
    TextField tf;
    Panel northp, centerp, southp;
    CheckboxGroup cg;

    public HelloEventTest()
    {
        setTitle("안녕이벤트");

        cg = new CheckboxGroup();
        bt_hello = new Button("안녕");
        bt_clear = new Button("지우기");
        bt_exit = new Button("종료");
        cb1 = new Checkbox("자바초급", cg, true );
        cb2 = new Checkbox("자바중급", cg, false );
        cb3 = new Checkbox("자바고급", cg, false );
        tf = new TextField(15);
        northp = new Panel();
        southp = new Panel();
        centerp = new Panel();


        northp.setLayout(new FlowLayout());
        northp.add(tf);
        northp.setBackground(Color.YELLOW);

        centerp.setLayout(new GridLayout(3, 1));
        centerp.add(cb1);
        centerp.add(cb2);
        centerp.add(cb3);

        southp.setLayout(new FlowLayout());
        southp.add(bt_hello);
        southp.add(bt_clear);
        southp.add(bt_exit);
        southp.setBackground(Color.RED);




        setLayout(new BorderLayout(3,1));
        add("North",northp);
        add("Center",centerp);
        add("South",southp);

        setSize(500,300);
        setVisible(true);


        eventUp();


    }//생성자

    private void eventUp()//이벤트 등록( 이벤트 소스의 수가 많을 때 )
    {
        //=======버튼=============
        bt_hello.addActionListener(this);
        bt_clear.addActionListener(this);
        bt_exit.addActionListener(this);

        //=======프레임============

        addWindowListener(new WindowAdapter() 
        {
           @Override
           public void windowClosing(WindowEvent e) 
           {
              System.exit(0);
           }
       });


    } //eventUp

    @Override
    public void actionPerformed(ActionEvent e)
    {   
        Object ob = e.getSource();

        //<데이터문자열> => String Label Text
        if(ob == bt_hello) {
            tf.setText("안녕");
        }else if(ob == bt_clear) {
            tf.setText("");
        }else {
        System.exit(0);
        }
    }

    public static void main(String[] args)
    {
        new HelloEventTest();   
    }
}
package com.encore.j0426;

import java.awt.Button;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class HelloEventTest extends Frame implements ActionListener{
  TextField tf;
  Checkbox cb1, cb2, cb3;
  Button bt_hello, bt_clear, bt_exit;

  Panel northp, centerp, southp;

  CheckboxGroup grade;

  public HelloEventTest() {
    setTitle("안녕이벤트");

    tf = new TextField(15);

    grade = new CheckboxGroup();


    cb1 = new Checkbox("자바초급",grade,true);
    cb2 = new Checkbox("자바중급",grade,false);
    cb3 = new Checkbox("자바고급",grade,false);

    bt_hello = new Button("안녕");
    bt_clear = new Button("지우기");
    bt_exit = new Button("종료");

    northp = new Panel();
    northp.setBackground(Color.YELLOW);
      northp.add(tf);

    centerp = new Panel();
    centerp.setLayout(new GridLayout(3,1));
      centerp.add(cb1);
      centerp.add(cb2);
      centerp.add(cb3);

    southp = new Panel();
    southp.setBackground(Color.PINK);
      southp.add(bt_hello);
      southp.add(bt_clear);
      southp.add(bt_exit);

    add("North",northp);
    add("Center",centerp);
    add("South",southp);

    setSize(300,300);
    setVisible(true);


    eventUp();
  }//생성자

  private void eventUp() {//이벤트 등록(이벤트 소스의 수가 많을 때)
      //============버튼==========================
      bt_hello.addActionListener(this);
      bt_clear.addActionListener(this);
      bt_exit.addActionListener(this);

      //============프레임==========================
      addWindowListener(new WindowAdapter() {
           @Override
           public void windowClosing(WindowEvent e) {
              System.exit(0);            
           }});
  }//eventUp

  @Override
  public void actionPerformed(ActionEvent e) {//이벤트 핸들러 (기능 추가)
     //System.out.println("action!!");
     Object ob = e.getSource();//이벤트를 발생시킨 소스의 참조변수(주소)를 얻어오기
     //ob= (bt_hello 또는 bt_clear 또는 bt_exit의 주소)


     //<데이터 문자열> ---> String, Label, Text

     //(메모리)주소비교  :  ==   !=
     if(ob==bt_hello) {//안녕 버튼클릭시
         //System.out.println("텍스트값:"+tf.getText());
        /* 
        if(cb1.getState()) //자바초급 Checkbox가 선택되었다면
         tf.setText("자바초급안녕~!!");
        else if(cb2.getState())
         tf.setText("자바중급안녕~!!");
        else //if(cb3.getState())
         tf.setText("자바고급안녕~!!");
        */
      Checkbox cb = grade.getSelectedCheckbox();//체크박스 그룹안에서 선택된 체크박스 얻어오기;  
        //cb = 선택에 따라  cb1, cb2, cb3
           tf.setText(cb.getLabel()+"안녕~!!!");
       /*
        if(cb==cb1) //자바초급 Checkbox가 선택되었다면
             tf.setText("자바초급안녕~!!");
        else if(cb==cb2)
             tf.setText("자바중급안녕~!!");
        else //if(cb==cb3)
             tf.setText("자바고급안녕~!!");
        */

     }else if(ob==bt_clear) {//지우기 버튼 클릭시
         //tf.setText(null);
         tf.setText("");

     }else {//if(ob==bt_exit)  종료 버튼 클릭시
         System.exit(0);
     }
  }//actionPerformed

  public static void main(String[] args) {
      new HelloEventTest();
  }
}
package j0426;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

//이벤트 소스: Scrollbar
// API  ----> addAdjustmentListener(AdjustmentListener l)

public class ColorChange extends Frame implements AdjustmentListener{
   Scrollbar sb_red, sb_blue, sb_green; 
   TextArea ta; 

   Panel bigp, p1,p2,p3;


   public ColorChange() {
     setTitle("색바꾸기");     

     //new Scrollbar(orientation, value, visible, minimum, maximum)
     sb_red = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);
     sb_blue = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);
     sb_green = new Scrollbar(Scrollbar.HORIZONTAL,0,10,0,265);

     ta = new TextArea();
      ta.setBackground(Color.black);

     p1 = new Panel();
     p2 = new Panel();
     p3 = new Panel();

     bigp = new Panel();

     //속성지정
     p1.setLayout(new BorderLayout());
      p1.add("West",new Label("빨강"));
      p1.add("Center",sb_red);

     p2.setLayout(new BorderLayout());
      p2.add("West",new Label("파랑"));
      p2.add("Center",sb_blue);

     p3.setLayout(new BorderLayout());
      p3.add("West",new Label("초록"));
      p3.add("Center",sb_green);

     bigp.setLayout(new GridLayout(5,1,0,10));
      bigp.setBackground(Color.orange);
      bigp.add(new Label());
      bigp.add(p1);
      bigp.add(p2);
      bigp.add(p3);

     setLayout(new GridLayout());
      add(bigp);
      add(ta);

     setSize(600,300);
     setVisible(true);

     eventUp();
   }//생성자 

   private void eventUp() {//이벤트 소스 등록
      sb_red.addAdjustmentListener(this); 
      sb_blue.addAdjustmentListener(this); 
      sb_green.addAdjustmentListener(this); 

      addWindowListener(new WindowAdapter(){//익명의 내부클래스 
           public void windowClosing(WindowEvent e) {
               System.exit(0);}});

   }

   @Override
   public void adjustmentValueChanged(AdjustmentEvent e) {//이벤트 핸들러
      System.out.println("adjust!!");
      //기능 추가
      int r = sb_red.getValue(); //빨강 스크롤바의 조절바 위치값 얻어오기
      int b = sb_blue.getValue(); //파랑 스크롤바의 조절바 위치값 얻어오기
      int g = sb_green.getValue(); //초록 스크롤바의 조절바 위치값 얻어오기

      System.out.println("red="+ r+", green="+g+", blue="+b);
      /*
        <TextField tf에게  텍스트 주기>
           tf.setText("전달문자열");
        <TextAread ta에게  텍스트 주기>
           ta.setText("전달문자열"); - 이전텍스트 clear, 새로운 텍스트를 덮어쓰기
           ta.append("전달문자열");  - 이전텍스트에 이어쓰기
       */

      //ta.setText("red="+ r+", green="+g+", blue="+b);
      ta.append("red="+ r+", green="+g+", blue="+b+"\n");

      ta.setBackground(new Color(r,g,b));

   }
   public static void main(String[] args) {
      new ColorChange();
   }

}

190425_Day14 복습,

버튼

  • checkbox

  • GUI => AWT => SWING


package Mission;

import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.TextArea;


public class CheckboxTest extends Frame
{
    Checkbox cb1, cb2, cb3, cb4;
    Label la;
    TextArea ta;

    Panel northp, southp;

    CheckboxGroup genderGroup;


    public CheckboxTest(String title)
    {
        super(title);

        genderGroup = new CheckboxGroup();

        cb1 = new Checkbox("사과");
        cb1.setBackground(new Color(10, 200, 30));
        cb2 = new Checkbox("딸기");
        cb2.setBackground(new Color(10, 200, 30));

        cb3 = new Checkbox("남자", genderGroup, true);
        cb3.setBackground(new Color(220, 100, 30));
        cb4 = new Checkbox("여자", genderGroup, false);
        cb4.setBackground(new Color(220, 100, 30));

        la = new Label("성별  :  ");
        ta = new TextArea();

        Panel northp = new Panel();
        //northp.setLayout( new FlowLayout ( ) ); // 기본이 Flow라 생략 가능
        Panel southp = new Panel();

        northp.add("사과",cb1);
        northp.add("딸기",cb2);
        northp.setBackground(new Color(10, 200, 30));

        southp.add(la);
        southp.add("남자",cb3);
        southp.add("여자",cb4);
        southp.setBackground(new Color(220, 100, 30));


//      setLayout(new BorderLayout()); //기본이라 생략 가능
        //보더 레이아웃의 경우에는 컴포넌트를 붙일 위치를 지정.
        add("North", northp);
        add("Center", ta);
        add("South", southp);

        //마무리( 프레임사이즈, 보이기 )
        setSize(300,300);
        setVisible(true);   
    }

    public static void main(String[] args) 
    {
        new CheckboxTest("체크박스테스트");
    }
}

package j0425;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//Frame에 FlowLayout을 설정
//Frame에 두개의 버튼을 배치하시오
//두개의 버튼의 변수명 : bt1(라벨 : "안녕"), bt2(라벨 : "잘가")
//bt1클릭시 화면 콘솔에 "안녕"을 출력하시오
//bt2클릭시 화면 콘솔에 "잘가"를 출력하시오



public class ButtonEventTest extends Frame implements ActionListener
{
    Button bt1,bt2;
    Label la1,la2;

    public ButtonEventTest()
    {
        bt1 = new Button("버튼1");
        bt2 = new Button("버튼2");
        la1 = new Label("안녕");
        la2 = new Label("잘가");

        setLayout(new FlowLayout());

        add(la1);
        add(bt1);
        add(la2);
        add(bt2);


        setSize(300,300);
        setVisible(true);

        //소스 <= 연결자 => 핸들러
        bt1.addActionListener(this);
        bt2.addActionListener(new C());
    }
        /*
         * public class Button
         * {
         *      public void addActionListener(ActionListener 1)
         *      {
         *          while(true)
         *          {
         *              if(버튼이 눌렸다면)
         *              {
         *                  l.actionPerformed();
         *              }
         *          }
         *      }
         * }
         */
    //생성자

    @Override
    public void actionPerformed(ActionEvent e) // 이벤트 핸들러 
    {//사건 발생시 실행할 기능 정의 

            System.out.println("안녕~!!");
//          System.out.println("잘가~!!");

    }
    public static void main(String[] args)
    {
        new ButtonEventTest();

    }


}

/===
package j0425;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class C implements ActionListener
{

    @Override
    public void actionPerformed(ActionEvent e)
    {
        System.out.println("잘가~!!");

    }

}
//이렇게도 가능 문자열 비교
package j0425;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//Frame에 FlowLayout을 설정
//Frame에 두개의 버튼을 배치하시오
//두개의 버튼의 변수명 : bt1(라벨 : "안녕"), bt2(라벨 : "잘가")
//bt1클릭시 화면 콘솔에 "안녕"을 출력하시오
//bt2클릭시 화면 콘솔에 "잘가"를 출력하시오



public class ButtonEventTest extends Frame implements ActionListener
{
    Button bt1,bt2;
    Label la1,la2;

    public ButtonEventTest()
    {
        bt1 = new Button("버튼1");
        bt2 = new Button("버튼2");
        la1 = new Label("안녕");
        la2 = new Label("잘가");

        setLayout(new FlowLayout());

        add(la1);
        add(bt1);
        add(la2);
        add(bt2);


        setSize(300,300);
        setVisible(true);

        //소스 <= 연결자 => 핸들러
        bt1.addActionListener(this);
//      bt2.addActionListener(new C());
        bt2.addActionListener(this);
    }
        /*
         * public class Button
         * {
         *      public void addActionListener(ActionListener 1)
         *      {
         *          while(true)
         *          {
         *              if(버튼이 눌렸다면)
         *              {
         *                  l.actionPerformed();
         *              }
         *          }
         *      }
         * }
         */
    //생성자

    @Override
    public void actionPerformed(ActionEvent e) // 이벤트 핸들러 
    {//사건 발생시 실행할 기능 정의 
        String str = e.getActionCommand();
        if(str.equals("버튼1"))
        {
            System.out.println("안녕~!!");
        }
        if(str.equals("버튼2")) 
        {
            System.out.println("잘가~!!");
        }
    }
    public static void main(String[] args)
    {
        new ButtonEventTest();

    }


}
//선생님 추천 코드
package com.encore.j0425;

import java.awt.Button;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/*
   <이벤트처리> ---> 컴포넌트에 기능을 정의하자!!

  1. 이벤트소스(컴포넌트)에 적용할 이벤트 분석  
         Button  bt    ------> ActionEvent 

  2. ActionListener(인터페이스)  ------>  implements ActionListener 
  3. public void actionPerformed(ActionEvent e){}  ===> 오버라이딩

  4. 연결자메소드 등록         [이벤트소스]  <------- 연결 ------->  [이벤트처리부]
          이벤트소스명.add인터페이스명(이벤트처리부의 위치);
           bt.addActionListener(this);

  <이벤트처리 방법>
  1. 기능을 적용할 컴포넌트 찾기(이벤트 소스 찾기!!): bt1, bt2
                                          ---------- 
                                                                          자료형  Button

  2. Button(이벤트소스)클래스의 메소드 중 add~Listener()메소드 찾기!!
                                ==> addActionListener() !!

  3. 인터페이스 (add제거) ==> ActionListener  : implements 하기!!
                                              ===> 메소드 오버라이딩 (이벤트 핸들러:기능정의)

  4. 연결자 등록!!  (2번의 add~Listener()메소드!! )                                                                                                                                                           
*/


public class ButtonEventTest extends Frame  implements ActionListener{
   Button bt1,bt2;//[이벤트 소스]

   public ButtonEventTest() {
      setTitle("버튼이벤트"); 
      bt1 = new Button("안녕");//203호
      bt2 = new Button("잘가");//303호


      setLayout(new FlowLayout());
      add(bt1);
      add(bt2);

      setSize(300,300);
      setVisible(true);

      //  소스  <----연결----> 핸들러
      //이벤트소스명.add~Listener(핸들러위치);
      bt1.addActionListener(this);
      //C c = new C();
      //bt2.addActionListener(new C());//(c);
      bt2.addActionListener(this);


      /*
         public class Button{

            public void addActionListener(ActionListener l){
                while(true){

                    if(버튼이 눌렸다면){
                        l.actionPerformed(이벤트소스의 정보);  
                    }

                }           
            }
         }    
      */


   }//생성자

   @Override
   public void actionPerformed(ActionEvent e) {//[이벤트 핸들러]
      //사건 발생시 실행할 기능 정의. 

      String str = e.getActionCommand(); //버튼의 라벨 문자열 얻기 
      //System.out.println("STR="+ str); 

      Object ob = e.getSource();
      //==> 이벤트를 발생시킨 컴포넌트(EventSource)의 주소를 리턴하는 메소드
      //'안녕'버튼 클릭시 Object ob = 203호;  Object ob = bt1;
      //'잘가'버튼 클릭시 Object ob = 303호;  Object ob = bt2;

      //if(str.equals("안녕"))
      if(ob==bt1) //주소를 비교
          System.out.println("안녕~!!");//0,1
      //if(str.equals("잘가"))
      else if(ob==bt2)
          System.out.println("잘가~!!");//0,1
   }

   public static void main(String[] args) {
       new ButtonEventTest();
   }

}

190424_Day13 복습, 예외처리, 오버라이딩, 내부클래스

복습

  • 예외

    • 프로그램 실행 중 발생하는 예기치 않은 사건 => 예외

    • 예외가 발생시 어떤 처리(대응)를 할지 추가코드 작성

    • 예외처리 : 자바언어를 더욱 강하게(robust)만드는 요소

    • 개발자 입장 : 코드량 증가

    • 사용자 입장 : 신뢰성 증가

    void hello() throws Exception
    {
        문장1;
        문장2;
        문장3;
    }
    //예외처리 전가!
    public static void main( String [] args)
    {
        hello();
    }
    • 예외처리 구문1 : try catch문
    void hello()
    {
        try
        {
        문장1;//AException 발생 가능성
        문장2;
        문장3;//BException 발생 가능성
    
        }catch(AException e)
        {
        } catch( )
        {
    
        }
    }
    //마치 if문 같은 느낌
    //e는 식별자이름규칙처럼 그냥 임의로 정해준다.
    //catch문 뒤에 이어서 catch문 작성 가능
    • 예외처리 구문2 : finally블럭

    • 혼자 사용 못하고 try catch랑 같이 사용

      void hello()
      {
        try
        {
            문장1;
            AException발생 가능 문장2;
            문장3;
            BException발생 가능 문장 4;
            문장5;
        }catch(AException e){문장6;}
        catch(BException e){문장 7;}
      }
      
      //예외발생 안함 (정상실행!) : 1;2;3;4;5;
      //AException발생! : 1; 6;
      //BException발생! : 1; 2; 3;
      //BException 발생시 만약 상속관계이고 A가 부모, B가 자식이라면 ... 안열림!
      //미션 문장5를 반드시 실행!
      //=> 이럴때 finally{} 사용한다.
      finally // catch문 뒤에
      {
        문장; // 보장해줄게!
      }
    • 에외종류

    • 체크(Checked) 예외

      public ststic void main(String[] args)
      {
        System.in.read();
      }
      //IOEception에러 발생!
      • 컴파일 에러 발생
      • 명시적으로 발생할 수 있는 예외에 대한 처리를 강요!
      • 반드시 try ~ catch 또는 throws를 사용해야함
    • 언체크(UnChecked) 예외

      public static void main( String[] args)
      {
        String []names = { "길동" , "주원" };
        System.out.println(names[3])
      };
      • 개발자실수 또는 사용자 입력데이터 예외

      • 컴파일시 에러가 발생하지 않는다.

      • 특징은 RuntimeException을 상속받는 예외 (자식)클래스!

      • try ~ catch 또는 throws 사용 가능

      • if문을 통해 처리 가능

      • 예)

      String []names = {"길동", "주원"}; //=> 배열 인덱스 0,1 생성
      System.out.println(names[2]); //=>컴파일 시에는 에러가 발생하지 않고 런타임 시 에러 발생
      • 퀴즈) 아래에서 에러가 발생하는 출력문은 무엇일까요?
      int a;
      void method()
      {
          int b;
          int c,d = 0;
          System.out.println(a); //O
          System.out.println(b); //X(에러발생), 변수를 초기화 하지 않았음
          System.out.println(c); //X, 변수를 초기화 하지 않았음
          System.out.println(d); //O
      
          int d,e;
          if(조건식) {d=100;}
          if(조건식) {e=200;}
          else {e = 300}
      
          System.out.println(e); //X, if문 실행 안할수도 있잖아, 초기화 하지 않았음
          System.out.println(f); //O, if문이나 else문 둘 중 하나는 반드시 값에 들어오기 때문에!  
      
          inf g;
      
          try
          {
              f=400;
          }catch(예외클래스명 변수명) {}
      
          System.out.println(names[2]); //X, 컴파일러 입장에서는 try도 if나 마찬가지임, 초기값 없어서 에러
      
      }
      package j0424;
      
      public class UncheckedExceptionTest 
      {
      public static void main(String[] args)
      //예외발생에 대해서 try~catch문 또는 throws를 사용하지 않고 처리하는 방법
      //=>> RuntimeException의 자식 Exception의 경우에만 가능
      {
          String names[] = { "길동", "주원" };
      
          int idx = 1;
          if (idx >= names.length)
          {
              System.out.println("인덱스를 확인하세요");
              return;
          }
      
          System.out.println(names[idx]);
      }
      }
      
      package j0424;
      
      public class UncheckedExceptionTest2
      {
      /*
       * String[] args = {"10", "4"};
       * 
       * su1 su2
       * =======
       * 10   5
       * ab   cd ==> NumberFormatException
       * 10   X ==> ArrayIndexOutofBoundsException
       * 10   0 ==> ArithmeticException
       * 
       */
      
      public static void main(String[] args)
      {
          try
          {
              System.out.println("매개변수로 받은 두개의 수");
              int su1 = Integer.parseInt(args[0]);
              int su2 = Integer.parseInt(args[1]);
              System.out.println("su1 = " + su1 + ", su2 = " + su2 );
              System.out.println("su1의 값을 su2로 나눈 몫" + (su1/su2));
              System.out.println("나눗셈을 잘 실행했니다~!");
          }
              catch (NumberFormatException e) 
          {
              //e : 에러메시지 객체
              e.printStackTrace(); // 문제가 발생한 코드와 연관된 메소드들의 호출 관계를 호출
              System.out.println("-------");
              System.out.println(e.toString()); //e.toString은 자체 프린트 기능은 없다, 예외 종류와 원인을 출력
              System.out.println("-------");
              System.out.println(e.getMessage()); //예외가 발생한 원인만 출력, 
              System.out.println("## 숫자만 입력하세요~!");
              return; // 메소드의 끝괄호 역할
          }catch (ArrayIndexOutOfBoundsException e) 
          {
              System.out.println(" ## 두개의 숫자를 반드시 입력하세요~!! ");
          }catch (ArithmeticException e) 
          {
              System.out.println(" ## 0으로 나눌 수 없습니다~!!");
          }
          //이렇게 안하고?! 이렇게 할 수도 있다!
      
          catch(Exception e)
          {
              System.out.println("모든에외처리" + e );
          }
          finally
          {
              System.out.println("Finally블록 (try 블럭내에서) 예외발생과 상관없이 반드시 실행!");
              //보통 FileSystem객체 또는 DataBase관련된 객체에 대한 반환
              //fr.close();   conn.close();
          }
      
          System.out.println("마지막 문장"); // 굳이 finally 안써도 이렇게 실행이 되네?, 단 리턴등의 값 넣었을때는 안나온다.
          //저런 ArithmeticException 이나 NUmberFormatException 모두 다 Exception에게 상속된것이기에!
          //다만 상황에 따라 다르게 쓰는것, Exception만 쓰면 간결하지만 자세하게 안됨
          //다중catch장점 : 다양한 예외에 대해 각각 알맞은 처리를 할 수 있다
      }//main
      
      }
      
    • < 사용자 정의 예외 >

    • 예외의 발생은 JVM에 의해 실행중 발생할 수도 있지만 사용자 프로그램에서 인위적으로 예외를 발생시킬 수 있다.(throw문을 제공)

    • 형식

      throw 예외객체;
      throw new 예외객체타입(매개변수);
      
      class MyException extends Exception
      {
        public ststic void main(String[] args)
        {
            super(msg);
        }
      }

<오버라이딩(메소드 재정의) 규칙>

class Parent
{
   접근제한자 void hello() throws A,B,C // throws는 책임전가!
   {

   }
}


class Child extends Parent
{
    //오버라이딩 메소드
    //오버라이딩시 주의할 점
    //  1.접근제한자는 부모와 동일한거나 확장해야 한다!
    //  2.throws는 부모와 동일하거나 또는 축소해야 합니다.

   접근제한자 void hello() throws A,B,C 
   {

   }
}
//=================
부모가 public hello(){} // 라면 
자식은 public hello(){} // 자식도 퍼블릭이어야 한다. 퍼블릭 이상은 없으니까!

부모가 protected hello(){} //라면
자식은 protected, public hello(){} //protected 이상이어야 한다.

부모가 hello(){} //라면 자식은 default(생략가능), protected, public
부모가 private 라면 상속 안되니 무효!

부모가 public hello() throws AException, BException, CException {} 이라면

[정상 오버라이딩 throws]
자식 public hello() throws AException, BException, CException {}
자식 public hello() throws AException, BException{}
자식 public hello() throws AException{}
자식 public hello(){}

[에러나는 오버라이딩 throws]
자식 public hello() throws AException, BException, CException, DException {}// 처럼 다 넣어버리면....
자식 public hello() throws Exception{}// 도 마찬가지

<내부클래스(중첩클래스)>

  • 중첩클래스, 포함, Nested

  • 클래스 내에 또 다른 클래스를 구성하는 것.

  • 마치 뻐꾸기 같아,, 남의 집에 터를 잡고 아우터클래스(밖에 있는 클래스)의 메소드를 자기것처럼 써버리는것!

    [public/final/abstract] class A //외부클래스, Outer클래스, Top-level클래스
    {
      //필드
      //생성자
      //메소드
      //1차 자원 정의
    
      [protected, static가능]class B //내부클래스, Inner클래스, [protected, static가능] 외부는 불가
      {
          //2차 자원 정의
      }
    }
  • 보통 이와 같은 경우, 사용자가 내부로 바로 호출하는것이 아니라 외부를 거쳐서 내부를 호출함.

    • 외부 호출할때에는
    A a = new A();
    a.hello();
    • 내부 호출할때에는
    B b = new B();
    b.print();
    package j0424;
    
    
    
    class NestingClass
    {
        int i = 11;
    
        void hello()
        {
            System.out.println( "하이" );
            //외부클래스에서 내부클래스 자원 사용
    //      print();// 바로 에러남!, 내부클래스 직접접근 불가!
            NestedClass Nested = new NestedClass();
            Nested.print();
        }
    
    
        //===============
        class NestedClass //내부(inner) 클래스
        {
            int j = 22;
            void print()
            {
                System.out.println( "프린트~" );
            }
    
            //내부클래스에서 외부클래스 자원 사용!
            void callTest()
            {
                hello();
                System.out.println("i = " + i);
            }
        } //Nested
    }
    
    public class NestedCalssTest
    {   
        public static void main(String[] args)
        {
            //외부클래스에 정의되어있는것 int i , hello(), 내부클래스
            //내부클래스에 정의되어있는것 int j, print()
    
            //외부 클래스의 메소드 호출
            NestingClass nesting = new NestingClass();
            nesting.hello(); // 하이, 프린트~ 같이 출력됨
            System.out.println("=====================");
    
            //내부클래스의 메소드를 main()에서 직접호출 ~! 체크체크~!★
            //=>> 객체생성 : 외부클래스명.내부클래스명 참조변수명 = new 외생성자().new 내부생성자();
            NestingClass.NestedClass nested = new NestingClass().new NestedClass();
            nested.print();
        }
    
    }

인터페이스

  • TUI ( Text User Interface )

    • 프로그램 실행을 Text에 의존해서 실행.
    • ex) 메뉴에서 1을 누르면 추가, 2를 누르면 검색, 3을 누르면 종료
  • AWT( Abstract Window Toolkit )

    • GUI( Graphic User Interface ) 환경을 구축하기 위한 class들의 묶음

    • GUI와 관련된 class들의 묶음. java.awt.*;

      1. Component : Menu, Button, Label, Choice, Checkbox, List, TextField, TextArea, Scrollbar… (전부 앞문자 대문자?! 클래스네!)

      2. Container : Component의 객체를 생성한 후에 그 객체를 배치한다. (여기서는 도화지 판 정도로 생각!, 다른곳에서는 서버 관련 단어로 쓰인다.)

      Object

    ​ |

    ​ Component

    ​ |

    ​ Container

    | |

    Panel Window

    | |

    Applet Frame

    | |

    FlowLayout BorderLayout (Default)

    Panel : display(x) , 한 영역에 두개 이상의 컴포넌트를 붙일때 사용.
    컴포넌트 속성을 지정하기위해 사용.
    Frame : display(o)

    1. Event 처리: Component에 기능을 실제로 부여하는 것.

      • Container의 배치방법(LayoutManager)
        —-> 컴포넌트를 컨테이너에 어떻게 위치시킬지 방법을 정의.
      FlowLayout(가운데 정렬)
    가운데를 기준으로 해서 Component들이 배치.
    (Frame크기에 따라 배치가 변경)
      BorderLayout(방위정렬)
    방위에 따라 사용자가 임의 배치 가능 (동,서,남,북, 중앙)
    상대적으로 큰 영역데 강조할 컴포넌트를 배치.
      GridLayout(같은 크기 정렬, 행열표현 정렬)
    Container의 크기를 같은 크기로 나누어 Component를 붙인다.
      CardLayout(같은 위치 정렬)

    같은 위치에 여러개의 Component를 배치할 때 사용.

    package j0424;
    
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Frame;
    
    //BorderLayout : "Center"(주된 데이터, 컴포넌트를 표현)를 기준으로 동서남북 위치를 설정하는것.
    public class BorderTest extends Frame//필요한 객체 ( 컴포넌트, 컨테이너 ) 선언
    {
    Button b1, b2, b3, b4, b5;
    
    public BorderTest(String title)
    {
        //상위클래스 생성자 호출
        super(title); //유의할 점 super는 항상 맨 윗라인에!
        setTitle(" 새로운 타이틀 "); // 위처럼 상위 클래스 생성자 안 부르더라도 괜찮아! setTitle사용하면 위치도, 횟수도 상관이 없어!
    
        //멤머 객체 생성
        b1 = new Button("1");
        b2 = new Button("2");
        b3 = new Button("3");
        b4 = new Button("4");
        b5 = new Button("5");
    
        //속성설정 ( 프레임에 대한 레이아웃, 붙이기 )
    //        this.setLayout( new BorderLayout() );
        setLayout(new BorderLayout());
    
    //        this.add(b1);
        //BorderLayout (방위정렬)의 경우 컴포넌트를 붙일 위치( 동서남북 중앙 ) 를 함께 설정.
        //주의 ) 위치 문자열을 표현 할 때 첫글자 대문자 사용, 철자가 틀리면 에러!
        add("North", b1); //this생략 가능
        add("East",b2);
        add("South",b3);
        add("West",b4);
        add("Center",b5);
    
        //마무리 2개 ( 프레임 사이즈, 프레임 보이기 )
        setSize( 300, 300 );
        setVisible(true);
    
    }//생성자
    
    public static void main(String[] args)
    {
        new BorderTest("Border테스트");
    }
    }
    
    //상속은 부모가 갖는 속성을 다 가져오는것인데 생성자는 안따라 옴! 그래서 super사용 14번 line처럼! 상위클래스 생성자 호출
    
    • mission
    package j0424;
    
    import java.awt.Color;
    import java.awt.FlowLayout;
    import java.awt.Frame;
    import java.awt.Label;
    import java.awt.Panel;
    import java.awt.TextArea;
    import java.awt.TextField;
    
    public class TextFieldAreaTest extends Frame
    {
        TextField tf1, tf2;
        TextArea ta;
        Label la;
    
            public TextFieldAreaTest(String title)
            {
                super(title);
                tf1 = new TextField("기본값", 10); //상단
    //          new TextField(int columns); // columns 는 열이지만 여기서는 글자수가 들어가는 너비
    //          tf2 = new TextField(10); 
                tf2 = new TextField("하이.txt", 10);//하단
    
                ta = new TextArea();
                la = new Label ("파일 이름 : ");
    
                Panel northP,southP; //1. 작은 도화지, 언제사용? 한 영역에 두개 이상의 컴포넌트를 붙일 때
                         //2. 컴포넌트 속성을 지정하기 위해 사용
    
    
                northP = new Panel();
    
    //          northP.setLayout(new FlowLayout()); //한번 안쓰고 작업 해봄 밑에, Panel의 기본 레이아웃이 FlowLayout이기에 생략 가능
                northP.add(tf1);
                Color c1 = new Color(90,225,90); //매개변수의 각 정수는 0~255의 값
                northP.setBackground(c1);
                northP.setBackground(Color.pink);
                northP.setForeground(new Color(240,90,90));
    
    
    
                southP = new Panel(); //컨테이너
                southP.setLayout(new FlowLayout());
                southP.add(la);
                southP.add(tf2);
                southP.setBackground(new Color(240,90,90));
                southP.setForeground(Color.pink);
    
    //          setLayout(new BorderLayout()); //Frame의 기본 레이아웃 : BorderLayout이기에 생략 가능
                //BorderLayout의 경우, '위치설정;을 함께
    
    
                add("North", northP);
                add("Center", ta);
    //          add("South", tf2);
    //          add("South", la);
                add("South", southP);
    
                setSize(300,300);
                setVisible(true);
            }
    
    
        public static void main(String[] args)
        {
            new TextFieldAreaTest("TextFieldArea테스트");
        }//main
    
    }
    
궁금상자
    - 레이아웃에서 NorthSouth가 윈단 다 먹는데 좌우가 영역 다 먹으려면 어떻게 해야 할까

190423_Day12 복습, Vector실습, 예외처리


복습

  • Vector

    • 데이터를 담는 바구니

    • 가변길이배열, 저장할 데이터 수 일정치 않을 때

    • 객체(데이터)에 대한 참조를 갖는 배열(모든 자료형을 담을 수 있음)

    • Vector v = new Vector();

    • 클래스 Person =>> 데이터 저장(저장되는 곳 주목)

    • public class Person
      {
      public getName()
      {
          return "나길동"
      }
      }
      Person p = new Person();
      System.out.print(p.getName());
      //으로 출력하면 된다.
      Person [] person = {p};
      System.out.print(person[0].getName());
      //person[0]
      Vecrot<Person> v = new Vector<>();
      v.add(p);
      System.out.print(v.get(0).getName())
  • Vector를 이용하여 사람의 번호, 이름, 나이, 직업 =>> 저장, 조회, 수정, 삭제

    package mission;
    
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    /*
    *  - 반복적인 메뉴출력
    *    - Vector에 추가할 사람정보 입력, 수정할 번호와 사람정보, 삭제할 번호의 입력을 받는다.
    *    - 선택된 언어에 따라 PersonMenu의 메소드를 호출.
    */
    public class PersonMenuTest
    {
    public static void main(String[] args) throws IOException 
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        PersonMenu menu = new PersonMenu();
    
    
        String num;
        do 
        {
            System.out.println( " < 사 람 메 뉴 > " );
            System.out.println( "1.추가 2.검색 3.수정 4.삭제 5.종료" );
            System.out.print( "번호 입력 =>>" );
            num = in.readLine();//1~5까지의 문자열 입력
    
            switch ( num ) 
            {
                case "1":
                { 
                    System.out.println( "#추가할 사람" );
                    System.out.print("이름 : ");
                    String name = in.readLine();
                    System.out.print("나이 : ");
                    int age = Integer.parseInt(in.readLine()); 
                    System.out.print("직업 : ");
                    String job = in.readLine();
    
    
    //                    menu.insert(name, age, job); // 메소드 호출 , ()안에는 데이터 넣기//데이터 나열해서 호출
    //                    String []arr = {name, age, job};
    //                    menu.insert(arr); 로 할 수도 있었다~! 문자열들을 배열로 묶어서 전달 호출
    
                    Person p = new Person(0, name, age, job); //no넣을수 없어서 아직...
                    //관련있는 4개의 데이터를 p변수로 묶고
                    menu.insert(p);
                }   
                    break;
                case "2": 
                    menu.select();
    
                    break;
                case "3": 
                    System.out.print("수정할 번호 : ");
                    int no = Integer.parseInt(in.readLine());
                    System.out.print("나 이 : ");
                    int age = Integer.parseInt(in.readLine());
                    System.out.print("직 업 : ");
                    String job = in.readLine();
    
                    //세개의 변수(no,age,job)를 변수명 한개로 묶어주기
    //                    Person p = new Person(no, null, age, job); //이렇게 해도 되고!
                    Person p = new Person(); // 0, null, 0, null
                        p.setNo(no); //no, null, 0, null
                        p.setAge(age); // no, null, age, null
                        p.setJob(job); // no, null, age, job
    
                    menu.update(p);//p넣으면 묶여서 전달된다.
                    break;
                case "4": 
                    System.out.println("#삭제하기");
                    int delNo = Integer.parseInt(in.readLine());
    
                    menu.delete(delNo);
    
    
                    break;
            }
            System.out.println();
    
        }while(!num.equals("5"));
        {
            System.out.println(" == E N D == ");
        }
    }
    
    
    }
    
    /===
    
    package mission;
    
    import java.util.Vector;
    
    /*
    *    - 기능을 정의하는 클래스
    *    - 멤머변수 Vector<Person> persons; // 사람정보를 저장
    *    - int no; // Vector에 입력되는 Person내에 순차적인 번호 부여
    *  - 멤버 메소드(기능메소드) : 추가(insert, create) , 조회(select, find) , 수정(update, modify) , 삭제(delete, remove) <== 데이터 단위[사람]
    *            
    */
    public class PersonMenu 
    {
    Vector<Person> personV; //Person 데이터를 받겠습 ( 데이터 단위는 Person단위로 ), 기본값 null
     int no;
    
    public PersonMenu()
    {
        personV = new Vector<>(); //기본값 null
        //PMT에 넣어도 괜춘, 기본값 0
    }
    
    public void insert(Person p)
    //public void insert(String []arr)
    {
        //벡터에 사람정보를 저장하기 전에, 유일한 번호(no)를 생성해서 p에 전달
    
        p.setNo(++no); // 유일한 번호 부여
        personV.add(p);
    }
    
    public void select()
    {
        System.out.println("사람목록");
        for (int i = 0; i < personV.size(); i++) 
        {
    //            Person p = persons.get(i);
    //            System.out.println(p); //를 줄여서 밑에 껄로
            System.out.println(personV.get(i));
        }
    }
    
    public void update(Person newP)
    {
        for(int i = 0; i < personV.size(); i++)//일치하는 번호 찾기
        {
            //=====
            //Person p.getNo()
    
            //일치하는 번호 ( 수정할 번호 ) 찾기
            Person oldP = personV.get(i); //벡터(데이터저장소)에 저장된 개개의 사람정보
            if( oldP.getNo() == newP.getNo()) // 일치 번호 찾았다면
            {
                //여기다가 set을 해버리면 완전 지워지고 다시 새로 써버리는것이다...
                //수정작업 ( 나이, 직업만 )
                oldP.setAge(newP.getAge());
                oldP.setJob(newP.getJob());
            }
        }
    }
    
    public void delete(int delNo)
    {
        for (int i = 0; i < personV.size(); i++) 
        {
            Person oldP = personV.get(i);
            if(oldP.getNo() == delNo)
            {
                personV.remove(i);
                break;
            }
        }
    }
    }
    
    /===
    
    package mission;
    
    /*
    * 자바빈즈, (서로 관련있는 속성들을 표현, 저장 하는 클래스
    *    - private속성 : 번호 이름 나이 직업
    *    - 생성자(선택사항)
    *    - public 게터메소드 세터메소드
    */
    
    public class Person {
     //속성정의
    private int no;
    private String name;
    private int age;
    private String job;
    
      public Person() {
    
    }
    
    public Person(int no, String name, int age, String job) {
        this.no = no;
        this.name = name;
        this.age = age;
        this.job = job;
    }
    
    public int getNo() {
        return no;
    }
    
    public void setNo(int no) {
        this.no = no;
    }
    
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getJob() {
        return job;
    }
    
    public void setJob(String job) {
        this.job = job;
    }
    
    @Override
    public String toString() {      
        return no+": ["+name+","+age+","+job+"]";
    }
    
    
    }//class Person

예외처리 < Exception >

  • 프로그램 실행 중에 발생하는 예기치 않은 사건
  • 자바는 프로그램 실행 중 발생할 수 있는 예외를 처리할 수 있는 기법 제공
  • 발생하는 모든 예외를 객체로 취급, 예외 관련 클래스 제공
  • 예)
    • 배열의 첨자가 음수값을 가지는 경우
    • 배열 첨자가 배열의 크기를 벗어나는 경우
    • 부적절한 형변환이 일어나는 경우
    • int su = 3.14 // 에러 -> int형에서는 0.14에 대한 표현 불가
    • int su = (int)3.14 // 실행가능, su변수에 3저장
    • double d = 30;
    • double d = 30; //묵시적인 형변환! d변수에 30.0dl wjwkd
    • double d = (double)30; //명시적인 형변환, 값은 같다.
    • (int)”홍길동” //에러발생 : String과 int자료형은 공통점이 없다.
    • (B)A //에러발생한다면 : A클래스와 B클래스간의 상속관계가 없다.
    • (Object)String // 가능하다, 모든 데이터는 최상위 클래스인 Object로 형변환 가능
    • Object ob = (Object)”나길동”; //가능
    • => 부모캐스팅은 보통 생략, Object ob = “나길동”; 이렇게!
    • ob.length() ? (안된다!) , ob는 부모… 자식 레퍼런스 호출 불가!
    • ob.toString() ? (), toString() Object에도 있는걸?, 그럼 toString()메소드는 어떤 클래스의 메소드일까? String!! (오버라이딩메소드이다!)
    • (String)Object =>> 자식캐스팅 : 반드시 명시를 해야 하는 부분!
    • String str = (String)ob;
    • str.length() =>> 3 (O)
    • (Parent)Child데이터 (Child)Parent데이터 =>> 상속관계가 있었을 때만 캐스팅이 가능
  • 입축력시 인터럽트가 발생하는 경우
    • 입출력하기 위해 지정한 파일이 존재하지 않거나 파일 이름이 틀린 경우.
  • throws 는 책임전가… !

<예외처리 구문 형식>

  • 이전의 throws 문은 예외가 발생시 할일에 대해 전가의 뜻을 가짐.

    void gildong() throws IOException
    {
    readLine(); //에러 발생하니 throws추가  
    }
    /*
    =>> gildong()메소드를 실행하다가 만약 IOException이 발생하면 그 상황에 대한 처리를 lime()메소드가 하시오!!
    */
    void lime()
    {
      readLine();
    }
  • try ~ catch문

    • 형식
    try
    {
        1;//1번에서 에러 발생시 2,3번 실행 안함!
        2;
        3;
    //예외가 발생할 가능성이 있는 문장; =>>대체적으로 메소드 호출 문장
    }catch(예외타입 변수명)//변수선언이 들어간다.(int이런 기본타입 말고 , 클래스 타입)
    {
        실제 예외가 발생 한다면 처리할 문장
    }finally{
        //예외발생과 상관 없이 반드시 실행할 문장;
    }
    
    //예외처리 case1) 각각 처리
    try
    {
        AException이 발생할 가능성 있는 문장1;
    }catch(AException e)
    {
        AException 발생시 처리할 문장
    }
    
    try
    {
        BException이 발생할 가능성 있는 문장2;
    
    }catch(BException e)
    {
        BException 발생시 처리할 문장
    }
    
    try
    {
        CException이 발생할 가능성 있는 문장1;
    }catch(CException e)
    {
        CException발생시 처리할 문장
    }
    
    //예외처리 case2) 다중catch를 사용 : 일반적으로 많이 사용
    try
    {
        AException이 발생할 가능성 있는 문장1;
        BException이 발생할 가능성 있는 문장2;
        CException이 발생할 가능성 있는 문장3;
    }catch(AException e){
        AException발생시 처리할 문장;
    }catch(BException e){
        BException발생시 처리할 문장;
    }catch(CException e){
        CException발생시 처리할 문장
    }
    • 다중 catch사용시 주의할 점!

      • 부모 자식 클래스 정의하는 순서에 주의~!

      • 자식클래스에 대한 catch문을 먼저 정의를 해야함!

      • 1번

      • catch(ParentException pe){} //ParentException pe = new ParentException(); , ParentException pe = new ChildException();
      • catch(ChildException ce){} =>> x

      • 2번

      • catch(ChildException ce){}
      • catch(ParentException pe){} =>> o
      • 위에서 1번에서 에러 발생, 결국 Parent에서 자식 에러까지 캐치해버림, 그래서 밑에 캐치문이 실행이 안됨!
      • 차일드와 차일드 비교하고, 넘어감
package j0423;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/*
 * < 자바 I/O 의 4대 클래스 > =>> 추상클래스
 * 
 *          byte단위              문자단위
 * -----------------------------------------------
 *  읽기      InputStream         Reader          =>> 대표 메소드 : read()
 *  쓰기      OutputStream        Writer          =>> 대표 메소드 : write() 
 *  
 */
public class ExceptionTest 
{
    public static void main(String[] args) 
    {
        //텍스트 파일 (a.txt)를 읽어서 그 내용을 콘솔(모니터)에 출력

        try {
            FileReader fr = new FileReader("bin/mission/b.txt"); // src좌표보다는 bin이 더 좋다! 최상위 경로에 넣어놓은 a.txt, FileNotFoundException 에러 발생(자식)
//          System.out.println(fr.read()); //IOException에러 발생 (부모)
//          System.out.println(fr.read()); //IOException에러 발생 (부모)
//          System.out.println(fr.read()); //IOException에러 발생 (부모)
//          System.out.println(fr.read()); //IOException에러 발생 (부모)
//          System.out.println(fr.read()); //IOException에러 발생 (부모) // -1 이 나오면 읽을 문자가 없다는 뜻
            int i ;
            while( ( i=fr.read() ) != -1 )
            {
                System.out.print((char)i);
            }
            System.out.println("\n파일 읽기 성공 :)");
        } catch (FileNotFoundException e) 
        {
            System.out.println("파일경로를 확인하시와요");
//          e.printStackTrace();
        } catch (IOException e) 
        {
            System.out.println("입출력에러가 발생했아와요");
//          e.printStackTrace();
        }

    }
}
궁금상자
    - 벡터안에 배열 ?
    - switch문에 fianl String?

190422_Day11 복습, String, Vector

복습

  • NullPointException 발생원인

    • null이란 메모리 할당 되지 않은 것
  • String

    • substring(int 시작인덱스, int 끝인덱스)
    • 단, 시작인덱스 포함, 끝인덱스 미포함
  • str.charAt(int 인덱스)

    • 인덱스에 해당하는 한 문자 리턴
  • 컴퓨터는 ‘a’문자를 내부에서 아스키코드 97로 인식

  • 문자열 공백 제거 str.trim();
  • 문자열 내용 비교 비교할대상.equals(비교할대상)
    • 소문자 대문자는 다르게 비교
    • 대소문자 상관없이 하고 싶다면 toUpperCase() 혹은 toLowerCase()로

- 물론 .equalsIgnoreCase() 가 있다 (자바는, SQL등에선 위의 방식)

  • 미션풀이

    • “`java
      package j0422;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    public class NameMenuTest
    {
    public static void main(String[] args) throws IOException
    {
    // 반복되는 메뉴출력( 화면 뷰 처리 )
    // 번호 입력을 위한 read() 또는 readLine() 메인에서 사용
    // 이름 입력을 위한 readLine() 메인에서 사용
    // 그러니까 통일성 위해 그냥 readline()쓰는게 좋겠넵…
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    NameMenu menu = new NameMenu();

        int no = 0;
        int cnt = 0;
    
    
        do
        {
            System.out.println("<이름메뉴>");
            System.out.println("1.추가  2.검색  3.수정  4.삭제  5.종료");
            System.out.print("번호를 입력해 주세요~ =>>");          
            String noStr = in.readLine();//문자열검사, 숫자로 구성되어있는지!
    
            boolean flag = menu.checkNum(noStr);
            if( !flag ) //( flag == false )
            {
                System.out.println("번호만 입력하세요");
                continue; // 제어문 
                //break : 스위치 혹은 반복문 종료,do while문 벗어남, 
                //continue : 반복문을 계속 진행, for문(증감자를 거친 조건식으로 이동), do-while문(조건식으로), while문(조건식으로) 
                //return : 메소드 프로그램 종료
            }
    
    
            no = Integer.parseInt( noStr ); // no에는 "1" "2" "3" 과 같은 문자열이 들어온다~!
    
            switch(no)
            {
            case 1 : { // 밑에 또 case3 에name이 등장하기 때문에(다시 밑에도 이름 바꿈) 영역괄호로 묶어버린다~!
                        if(cnt == 5)
                        {
                            System.out.println(" 더 이상 입력할 수 없습니다 \r\n " + " 한 개 이상의 이름을 먼저 삭제 한 후 입력하세요 ");
                            break; //switch 블록 벗어나기
                        }
                        System.out.print("이름 입력 : ");
                        String name = in.readLine();
    
                        if(menu.existName(name) ) // 중복된 이름을 발견했다면
                        {
                            System.out.println("이미 입력된 이름입니다!!");
                            break;
                        }
                        menu.add(name);
                        cnt++; // 유효성 검사 valid Check
    
                        //메소드호출 : 메소드명(데이터)
                        }
                        break;
    
            case 2 : 
                        menu.search();
                break;
    
            case 3 : 
                        System.out.print("변경하고자 하는 기존 이름 입력 : ");
                        String oldName = in.readLine();
    
                        if ( !menu.existName( oldName ) )
                        {
                            //수정할 이름이 존재하지 않는다면
                            System.out.println("존재하지 않는 이름입니다.");
                            break;
                        }
    
                        System.out.print("새로 수정 하는 이름 입력 : ");
                        String newName = in.readLine();
    
                        menu.update(oldName, newName);
                break;
    
            case 4 : 
                        System.out.print("삭제 할 이름 입력 : ");
                        String delName = in.readLine();
    
                        if ( !menu.existName( delName ) )
                        {
                            //수정할 이름이 존재하지 않는다면
                            System.out.println("존재하지 않는 이름입니다.");
                            break;
                        }
    
                        menu.delete(delName);
            }//switch
        System.out.println();
        }
        while( no != 5  ); //번호에 1,2,3,4,5 입력했다면! , String클래스이기 때문에 == 으로 하면 값이 아닌 주소를 찾는다., equals로! 
    
        System.out.println("E N D");
        //논리데이터 앞에는 !(not) 연산자를 붙일 수 있다~!
        //<!not연산자>
    
    }//main
    

    }

    /===

    package j0422;

    public class NameMenu
    {
    String names[]; // null

    public NameMenu()
    {
        names = new String[5];
    }
    
    //배열에 이름 저장
    public void add(String name)
    {
        //빈방찾기~!
        for( int i = 0 ; i < names.length; i++ )
        {
            if( names[i] == null ) //빈방을 찾았다면~!
            {
                names[i] = name;
                break;
            }
        }
    }
    
    //배열내의 이름들 조회
    public void search()
    {
        System.out.println("#이름목록");
        for( int i = 0; i<names.length; i++)
        {
            if(names[i] != null) 
                {
                System.out.println(names[i]);
                }
        }
    }
    
    //배열에 저장된 이름을 변경
    public void update(String oldName, String newName)
    {
        //oldName과 일치하는 이름을 배열에서 찾기
        for( int i = 0; i < names.length; i++) //배열 전체 인덱스
        {
    

    // if( names[i].equals( oldName ) )
    // {
    /*
    * NullpointerException 방지
    * 1. if(oldName.equals(names[i])) : oldName에 null값 절대 전달되지 않음
    * 2. if(names[i] != null && names[i].equals(oldName))
    * : names[i]번지의 값이 null이 아닐 때 equals()메소드 호출!
    */
    if(names[i] != null && names[i].equals(oldName))
    {
    names[i] = newName;
    break;
    }
    }

    }//update
    
    //배열에 저장된 이름을 삭제
    public void delete(String delName)
    {
        // 배열에 저장된 데이터 삭제표현 : 배열명[번지] = null;
        for( int i = 0; i < names.length; i++ )// 배열에서 삭제할 이름 찾기
        {
            if(names[i] != null)
            {
                if(names[i].equals(delName))
                {
                    names[i] = null;
                    break;
                }
            }
    
        }
    
    }//delete
    //추가 메소드 정의
    //문자열 데이터가 숫자 조합인지 체크
    public boolean checkNum( String str )
    {
        char ch;
        for( int i = 0; i < str.length(); i++ )
        {
            ch = str.charAt(i);
    
            if( ch < '0' || ch > '9' ) //숫자로 구성된 문자가 아니라면!
            {
                System.out.println("숫자만 입력하세요");
                return false;
            }
        }
        return true; // 전체 문자가 숫자로 구성되었다면
    }
    
    public boolean existName(String name)//중복(존재하는) 이름 체크
    {
        for(int i = 0; i < names.length; i++) //배열 인덱스
        {
            //null.equals("길동"); // NullPointerException발생
            //"길동".equals(null); //NullPointerException 발생 하지 않음
            if( name.equals(names[i] ) )
            {
                return true;
            }
        }
        return false;
    }//existName
    

    }
    “`


str.getBytes() str.toCharArray()
to <======= from =======>
byte []b = {97,98,99} String str = “abc”;
from =======> to <=======
new String(b); new String(ch);
package j0422;

public class StringTest2 
{
    public static void main(String[] args) 
    {
        String str = "abc";
        System.out.println("STR = " + str);

        byte[]b = str.getBytes();
        for (int i = 0; i < b.length; i++) 
        {
            System.out.println("b[" + i + "] = " + b[i] );
        }

        String str2 = new String(b);
        System.out.println("STR2 = " + str);

    }
}
package j0422;

public class StringTest 
{

    public static void main(String[] args) 
    {
        String str = "JavaProgramming";

        //특정 문자열로 시작하는 지 체크 boolean str.startsWith(String prefix)
        System.out.println("str은 'Jav'로 시작하는가?\n" + str.startsWith("Jav") + "\n");      
        System.out.println("str은 'Jav'로 시작하는가?\n" + str.startsWith("av") + "\n");       

        //특정 문자열로 끝나는지 체크 boolean str.endsWith(String suffix)
        System.out.println("str은 \"ing\"로 끝나는가? \n" + str.endsWith("ing") + "\n");

        //str.contains(CharSequence s)
        System.out.println("str이 \"pro\"를 포함하는가? \n" + str.contains("Pro") + "\n");

        String tel = "010-1234-5678";
        //tel 값은 02-123-4567 또는 053-123-5656 이렇게도 나올 수 있다.
        String teltel = "02-112-1119"; // 번호가 위의 식이 아니라면?!

        //문제 String tel1, tel2, tel3 변수를 선언하고 각각 "010", "1234", "5678"을 저장 후 
        //화면에 각 변수의 값을 출력하시오.
        //힌트 substring()메소드와 indexOf() 메소드를 사용

//      String tel1;
//      String tel2;
//      String tel3;
//      
////        
//      tel1 = tel.substring(0, 3);
//      System.out.println(tel1);
//      tel2 = tel.substring(4, 8);
//      System.out.println(tel2);
//      tel3 = tel.substring(9, 13);
//      System.out.println(tel3);

        int idx1 = teltel.indexOf("-"); //첫번째 "-"에 대한 인덱스
        int idx2 =teltel.indexOf("-", idx1 + 1); //두번째 "-"에 대한 인덱스
        System.out.println("idx1 = " + idx1 + "\nidx2 = " + idx2);
        idx2 = teltel.lastIndexOf('-');
        System.out.println("last index idx2 = " + idx2);

        String tel1 = teltel.substring(0, idx1);
        String tel2 = teltel.substring(idx1 + 1, idx2);
        String tel3 = teltel.substring(idx2 + 1);
        System.out.println("tel1 :" + tel1 + "\ntel2 :" + tel2 + "\ntel3 :" + tel3);
    }

}

/*
str은 'Jav'로 시작하는가?
true

str은 'Jav'로 시작하는가?
false

str은 "ing"로 끝나는가? 
true

str이 "pro"를 포함하는가? 
true

idx1 = 2
idx2 = 6
last index idx2 = 6
tel1 :02
tel2 :112
tel3 :1119
*/
package j0422;

import java.util.StringTokenizer;

public class StringTokenizerTest 
{

    public static void main(String[] args) 
    {
        //StringTokenizer : 문자열 데이터를 특정 구분자(delimiter)를 통해 분리해주는 클래스

        //StringTokenizer(String str, String delim) 생성자
        //str ==> 기준 문자열 (전체문자열), delim ==> 구분자
        //token(토큰) : 분리된 각각의 데이터
        String tel = "010-1234-5678";
        StringTokenizer st = new StringTokenizer(tel, "-");
        //st = ["010" , "1234", "5678"];

//      //토큰 데이터 꺼내오기 : String st.nextToken()
//      System.out.println(st.nextToken());
//      System.out.println(st.nextToken());
//      System.out.println(st.hasMoreTokens()); //st에 토큰 데이터 가지고 있으면 true
//      System.out.println(st.nextToken());
//      
//      
//      System.out.println(st.hasMoreTokens()); // st에 토큰 데이터 없다면 false
//      //System.out.println(st.nextToken());// 가져올 토근 데이터 초과하면 에러

        while(st.hasMoreElements())
        {
            System.out.println(st.nextToken());
        }
        System.out.println("=================");

        tel = "010-1234-5678";
        //String[] tel.split(String regex); //특정문자(매개변수)를 통해 데이터를 분리 - 결과는 문자열 배열
        //regex 는 정규식이라는 뜻
        //String[] tel.
        //split() 메소드는 빈문자열 ""도 저장해서 사용.
        String tels[] = tel.split("-"); // tels = {"010", "1234", "5678"};
        for (int i = 0; i < tels.length; i++) 
        {
            System.out.println("tels[" + i + "] = " + tels[i]);
        }
    }

}
package j0422;

public class MatchesTest 
{
    //String클래스 ==> boolean str.matches(String regex);
    //regex ==> regular expression( 정규표현식, 정규식 )
    //regex를 통해 전달되는 패턴에 str이 부합(match)된다면 true를 리턴.

    // 출현(발생)횟수 관련된 부호 : ?(0,1) , *(0~무한대) , +(1~무한대) 
    // 부호 없음 =>> 1번 출현
    // 
    public static void main(String[] args) 
    {
        String str = "";//false
        String str1 = "a";
        String str2 = "aa";
        String str3 = "";       
        String str4 = "abc";


                            //matches(패턴문자열)
        System.out.println("부호 없음\t:\t" + str.matches("[a]")); // a문자 한번 들어오기를 원한다!
        System.out.println("?부호\t:\t" + str1.matches("[a]?")); // a문자 : 0,1
        System.out.println("*부호\t:\t" + str2.matches("[a]*")); // a문자 : 0~무한대
        System.out.println("+부호\t:\t" + str3.matches("[a]+")); // a문자 : 1~무한대
        System.out.println("=================");
        System.out.println(str4.matches("[abc]")); //a또는 b또는 c문자 중 하나가 오직 1번        
        System.out.println(str4.matches("[abc]+")); //a또는 b또는 c문자 중 하나가 오직 1번

        String name = "jinju";
        //name변수에 대한 영문자 체크 !
        System.out.println("name변수의 이름체크(영어 소문자) : " + 
                name.matches("[qwertyuiopasdfghjklzxcvbnm]+"));
        //표현식 사용시 대괄호[]안에 '-'부호는 범위를 표현
        System.out.println(name.matches("[a-zA-Z]+")); //영문자 상관 없이 다 

        String su = "4567898765456";
        System.out.println("숫자체크 : " + su.matches("[0-9]+")); // 


        /*
         * 이제 이거 쓰면
         * 입력 받을 때 숫자만 입력하길 원한다면
         * if(!noStr.matches("[0-9]+"))
         * {
         *  //조건문~!
         * }
         * 이렇게 편하게 쓸 수 있다.
         */

        String hangul = "진주는자면서뿡뿡을한다그것도두번이나";
        //hangul 변수에 대한 한글 체크
        System.out.println("한글 체크 : " + hangul.matches("[ㄱ-힣]+"));

        String id = "aasdfgh123";
        //아이디는 8 ~ 12자리, 영문자와 숫자 조합


        String idPattern = "[a-zA-Z0-9]{8,12}"; //문자열 길이 = 최소 8자리에서 12자리
        //{8,12} 8이상 12이하,  {8,} 최소 8이상, {8} 무조건 8글자

        System.out.println("아이디체크 : " + id.matches(idPattern));

        String juminBunho = "931025-2022334";
        String juminPattern = "[\\d]{6}-[\\d]{7}";
        System.out.println("주민번호체크 : " + juminBunho.matches(juminPattern));
    }
}
package j0422;

public class StringConvertTest 
{

    public void convert1()
    {
        String s1 = "우리나라";
        String s2 = "대한민국만세";
        s1 = s1+s2;
        /*
         * String 클래스 : 고정(길이)문자열!
         * 1. String클래스 객체 생성
         * 2. 문자열 변환을 위해서 임시로 StringBuffer 클래스 객체 생성
         * 3. 내부에서 append() 메소드 호출
         * 4. StringBuffer객체를 다시 String객체로 변환
         * 5. 임시생성된 StringBuffer객체를 소멸
         * 이럴경우 가급적 s3이라는 변수 만들어서 넣는게 좋다!
         */
        System.out.println(s1);
    }

    public void convert2()
    {
        StringBuffer s1 = new StringBuffer("우리나라");
        s1.append("대한민국만세");
        /*
         * StringBuffer 클래스 : 가변(길이)문자열!
         * 1. StringBuffer클래스 객체 생성
         * 2. append() 메소드 실행
         */
        System.out.println(s1);
    }

    public void kan()
    {
        System.out.println("================");
    }
    public static void main(String[] args) 
    {
        StringConvertTest sct = new StringConvertTest();
        sct.convert1();
        sct.kan();
        sct.convert2();
    }

}

  • <배열 사용이유>

    • 여러개의 데이터를 한 변수명으로 정의 =>>(인덱스) 관리가 편해짐
    • 제약 : 동일한 자료형, 고정된(수) 데이터만 입력!
  • <벡터> : 데이터들을 담는 바구니

궁금상자 
    - matches에서 띄어쓰기까지 포함된거 검색하려면 띄어쓰기 제거 후?!

    * 바보야 String 비교는 .equals야....

    - break, continue, return이 헷갈려

190519_Day10 복습, 미션풀이, not연산자, NullPointException, String

복습

  • 속성변수와 참조변수의 차이점

    • 속성변수

    • 데이터 값(value)를 담는 변수

    • 자료형 변수명;

    • 사용

      no = 300;
      System.out.println( no );
      System.out.println( no + 200 );
      System.out.println( no. ); //얘는 에러
    • 참조변수

    • 데이터 주소( addr )를 담는 변수

    • 자료형 변수명;

      • String Integer A NameMenu Person 등…
      A a; // a에 주소를 담겠음
      a = new A();
      
      System.out.println( a.su );
      System.out.println( a.hello() );
    • 정수 100 =>> 데이터 저장

    • 저장되는곳에 주목

    • 변수 : int su = 100; System.out.println( su );

    • 배열 : int su[] = { 100 }; int su[] = new int[3]; su[0] = 100;

    • 클래스

      class A
      {
        int su = 100;
      }
      A a = new A();
      
      출력은 System.out.println( a.su );
  • 속성변수와 참조변수 차이점 2

    • 값복사와 주소 복사
    int su1;
    int su2;
    
    su1 = 100;
    su2 = su1;
    //su1이 가지고 있는 데이터를 su2에 전달( 그릇 말고 내용만 )
    su1 = su1 * 200;
    // su1 : 20000 su2 : 100 아! 100이란 값은 두개가 있었구나, 주소가 다르구나
    A a1;
    A a2;
        a1 = new A(); 203호 메모리 가르킴
        a1.su = 100; //메모리 값 100으로 바뀜
        //a1.su 출력  : 100
        a2 = a1; // a2도 203호(가칭) 메모리를 가르킴

미션풀이

// 로또 중복 없이 6개 출력
import java.util.Random;

public class LottoTest 
{
    public static void main(String[] args) 
    {
        int lotto [ ] = new int [ 6 ];
        Random r = new Random();

        lotto[ 0 ] = r.nextInt( 6 ) + 1; // 0~44 까지라 1더하기!
        do 
        {
            lotto[ 1 ] = r.nextInt( 6 ) + 1; 
        }while(lotto[1]==lotto[0]);

        do
        {
            lotto[ 2 ] = r.nextInt( 6 ) + 1;
        }while( lotto[2] == lotto[1] ||
                lotto[2] == lotto[0]);

        do
        {
            lotto[ 3 ] = r.nextInt( 6 ) + 1;
        }while( lotto[3] == lotto[1] || 
                lotto[3] == lotto[0] || 
                lotto[3] == lotto[2]);

        do
        {
            lotto[ 4 ] = r.nextInt( 6 ) + 1;
        }while(lotto[4] == lotto[1] || 
                lotto[4] == lotto[0] || 
                lotto[4] == lotto[2] ||
                lotto[4] == lotto[3]);
        do
        {
            lotto[ 5 ] = r.nextInt( 6 ) + 1;
        }while( lotto[5] == lotto[1] || 
                lotto[5] == lotto[0] || 
                lotto[5] == lotto[2] ||
                lotto[5] == lotto[3] ||
                lotto[5] == lotto[4]);

        for( int i = 0; i < lotto.length; i++ )
        {
            System.out.println("lotto[" + i + "] = " + lotto[i]);
        }
    }
}
//로또
import java.util.Arrays;
import java.util.Random;

public class LottoTest2 
{
    int lotto[]; // null
    Random r; // null

    public LottoTest2() 
    {
        lotto = new int[6];
        r = new Random();
    }//생성자

    public void printNum() 
    {
        for (int i = 0; i < lotto.length; i++) 
        {
            System.out.print( lotto[ i ] + "\t");//6번
            if( i < 5 )System.out.print("\t");//5번
        }
    }

    public void generateNum()
    {
        for (int i = 0; i < lotto.length; i++ )
        {
            lotto[ i ] = r.nextInt(45) + 1; // 1에서 45까지 난수 발생!
            //세번째 데이터를 입력 i =>> 2

//          boolean flag = duplicateNum(i);
//          if(flag)
//          {
//              i--;
//          } 이를 줄여서 아래에
            if(duplicateNum(i))i--;

        }//for문
        Arrays.sort(lotto);
    } //generateNum

    //중복숫자 체크 기능, 중복 숫자 발견시 true 리턴~!
    public boolean duplicateNum(int idx)
    {
        for( int i = idx - 1; i >= 0; i--) //1~0 , 
        {
            if( lotto[idx] == lotto[i] )
            {
                return true;
            }
        }//for
        return false; // for문을 다 실행한 다음에 내려옴. if를 한번도 만족하지 않았다. 중복된 데이터를 찾기 못했다.
    }//duplicateNum

    public static void main(String[] args) //생성자 : 초기화 메소드, 선행작업
    {
        LottoTest2 lotto = new LottoTest2(); // 생성자 먼저 호출

        for(int i = 1; i<6; i++)
        {
            System.out.print(i + "회 : ");

            lotto.generateNum();
            lotto.printNum();
            System.out.println(" ");
        }

    }
}
//다른 로또 방법도 있다 45개 짜리 배열 만들고 랜덤으로 섞고 0번부터 5번까지 꺼내오기
import java.util.Arrays;
import java.util.Random;

public class LottoTest3 
{
    public static void main(String[] args) 
    {
        int[] lotto = new int [45]; // 인덱스 0~44
        Random r = new Random();

        //첫번째 방 ~ 마지막 방 숫자 입력 : 1~45
        for (int i = 0; i < lotto.length; i ++)
        {
            lotto[i] = i + 1;
        }

        //숫자를 섞어주기
        int temp;
        for(int i = 0; i<1000; i++) 
        {
            int randomIdx = r.nextInt(44) + 1; // 밑에서 랜덤이 두번 쓰이는데 같은곳을 지정하기 위해 미리 변수 선언
            temp = lotto[0];
            lotto[0] = lotto[randomIdx]; //0부터 44번지 + 1 중, 한개!
            lotto[randomIdx] = temp;        
        }


        for ( int i = 0; i < 6; i ++) // 배열 맨 앞의 6개 숫자를 출력
        {   Arrays.sort(lotto, 0, 6);
            System.out.println( "lotto[" + i + "] = " + lotto[ i ] );
        }
    }
}

package nameManuMission;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class NameMenuTest 
{
    public static void main(String[] args) throws IOException 
    {
        // 반복되는 메뉴출력( 화면 뷰 처리 )
        // 번호 입력을 위한 read() 또는 readLine() 메인에서 사용
        // 이름 입력을 위한 readLine() 메인에서 사용
        // 그러니까 통일성 위해 그냥 readline()쓰는게 좋겠넵...
        NameMenu menu = new NameMenu();
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String no;
        do
        {
            System.out.println("<이름메뉴>");
            System.out.println("1.추가  2.검색  3.수정  4.삭제  5.종료");
            System.out.print("번호를 입력해 주세요~ =>>");          
            no = in.readLine(); // no에는 "1" "2" "3" 과 같은 문자열이 들어온다~!

            switch(no)
            {
            case "1" : { // 밑에 또 case3 에name이 등장하기 때문에(다시 밑에도 이름 바꿈) 영역괄호로 묶어버린다~!
                        System.out.print("이름 입력 : ");
                        String name = in.readLine();
                        menu.add(name);
                        //메소드호출 : 메소드명(데이터)
                        System.out.println( name );
                        }
                        break;

            case "2" : 
                        menu.search();
                break;

            case "3" : 
                        System.out.print("변경하고자 하는 기존 이름 입력 : ");
                        String oldName = in.readLine();

                        System.out.print("새로 수정 하는 이름 입력 : ");
                        String newName = in.readLine();

                        menu.update(oldName, newName);
                break;

            case "4" : 
                        System.out.print("삭제 할 이름 입력 : ");
                        String delName = in.readLine();

                        menu.delete(delName);
            }//switch
        }
        while( !no.equals( "5" ) ); //번호에 1,2,3,4,5 입력했다면! , String클래스이기 때문에 == 으로 하면 값이 아닌 주소를 찾는다., equals로! 

        System.out.println("E N D");
        //논리데이터 앞에는 !(not) 연산자를 붙일 수 있다~!
        //<!not연산자>

    }//main
}
/===
package nameManuMission;

public class NameMenu 
{
    String names[]; // null

    public NameMenu()
    {
        names = new String[5];
    }

    //배열에 이름 저장
    public void add(String name)
    {
        //빈방찾기~!
        for( int i = 0 ; i < names.length; i++ )
        {
            if( names[i] == null ) //빈방을 찾았다면~!
            {
                names[i] = name;
                break;
            }
        }
    }

    //배열내의 이름들 조회
    public void search()
    {
        System.out.println("#이름목록");
        for( int i = 0; i<names.length; i++)
        {
            if(names[i] != null) 
                {
                System.out.println(names[i]);
                }
        }
    }

    //배열에 저장된 이름을 변경
    public void update(String oldName, String newName)
    {
        //oldName과 일치하는 이름을 배열에서 찾기
        for( int i = 0; i < names.length; i++) //배열 전체 인덱스
        {
//          if( names[i].equals( oldName ) )
//          {
                /*
                 * NullpointerException 방지
                 * 1. if(oldName.equals(names[i])) : oldName에 null값 절대 전달되지 않음
                 * 2. if(names[i] != null && names[i].equals(oldName))
                 *      : names[i]번지의 값이 null이 아닐 때 equals()메소드 호출!
                 */
                if(names[i] != null && names[i].equals(oldName))
                {
                names[i] = newName;
                break;
                }
        }


    }//update

    //배열에 저장된 이름을 삭제
    public void delete(String delName)
    {
        // 배열에 저장된 데이터 삭제표현 : 배열명[번지] = null;
        for( int i = 0; i < names.length; i++ )// 배열에서 삭제할 이름 찾기
        {
            if(names[i] != null)
            {
                if(names[i].equals(delName))
                {
                    names[i] = null;
                    break;
                }
            }

        }

    }//delete

}

NullPointerException 발생원인!

  • null이란 메모리 할당되지 않은 것을 의미한다.

  • 메모리 할당을 하지 않은 상태에서 필드 또는 메소드를 참조 했을 때 발생하는 에러!

  • null.필드명 null.메소드명(); 시 발생!

    class A
    {
      void hello()
      {
    
      }
    }
    
    class test
    {
      A a; //null
    
      void print()
      {
          a.hello(); //null.hello()한것과 같다, nullpoint에러
          a mew A(); // a에는 메모리 주소정보가 저장
          a.hello(); // 싫
      }
    
      public static void main(String []args)
      {
          Test t = new Test();
          t.print();
      }
    }
    aa.bb(dd); 
    =>> ㅁㅁ\\\\\\\\NullPointrExeption 을 발생 킬 수 있는 요소, 는? aa 90%, bb 1-%
    
    
    null.bb(dd); =>> 예외 발생
    aa.bb(null);  예회 발생하지 않음
    
    A aa;
    class A
    {
    
    }

String

package j0419;

public class StringTest 
{
    public static void main(String[] args) 
    {
//      String 자바 = "abc";
//      String str = 자바;

//      String 문자열 : 문자들의 나열!
        String str = "Java Programming";
        //인덱스 ```````012345678901234
        //총 문자 15개가 들어갔다. str은 참조변수, 클래스잖아~! 속성은 뒤에 . 안됨, 참조변수는 . 가능~!

        System.out.println(" 바꾼값 = " + str.replace("Java", "자바") );

        //str에서 부분 문자열 "Programming"을 구하시오.
        System.out.println(str.substring( str.indexOf('P') ));

        //str.substring(4);
        System.out.println("str.indexOf( \"am\" )" +str.indexOf( "am" ));

        //마지막 'a' 문자의 인덱스를 구하시오
        System.out.println("str.lastIndexOf( \'am\' )" +str.lastIndexOf( 'a' ));

        //문자열 치환(대체)
        System.out.println("str.replace('a', 'o') = " + str.replace('a', 'o'));

        //"JovoProgromming"이 str에 저장되길 원한다면
        str = str.replace('a', 'o');
        System.out.println("STR = " + str);


//      str.~ String클래스에 있는

        //문자열 길이( 문자 갯수 )
        System.out.println("str문자열길이( 문갯수 ) : " + str.length());

        //부분문자열 =>> "Pro" 문자열 얻기
        //substring( int beginIndex, int endIndex)
        System.out.println( "str.substring(4, 6) = " + str.substring( 4, 6 ) );//여기서 4,6은 파라미터
        //beginIndex : 시작인덱스( 포함 )
        //beginIndex :  끝 인덱스( 미포함 )
        //=>> str.substring( 4, 7 ) 은  인덱스4 ~ 인덱스6 까지

        //부분문자열 =>> "Programming" 문자열 얻기
        System.out.println(str.substring( 5, 8 ));
        System.out.println(str.substring( 5 )); // 시작인덱스부터 끝까지

        //특정인덱스의 문자 얻어오기 : char str.charAt(int index)
        System.out.println( "str.charAt(4) = " + str.charAt( 5 ) );

        //특정 문자의 인덱스 얻어오기
//      int str.indexOf(int ch);
        int index = str.indexOf(97); //97은 소문자 a
        int index2 = str.indexOf('a'); //97은 소문자 a
        System.out.println("index = " + index2);
        System.out.println("index = " + index);

        System.out.println( (char)97 );

        //replace(CharSequence target, CharSequence replacement)
        //CharSequence 부모 - String 자식
        str = "Java Programming";
        //문자열에 공백 추가~!
            str = " " + str + " "; //str 앞에 공백 2개 , 뒤에 공백 2개 추가 
            System.out.println( "공백 추가 후 STR = " + str );
            System.out.println( "STR문자열 길이 = " + str.length( ) );

            //문자열 제거! ( 문자열 앞 뒤 연속된 공백제거 ) 
            str = str.trim();
            System.out.println("공백 제거 후 STR = " + str );
            System.out.println( "STR문자열 길이 = " + str.length( ) );


    }
}
package j0419;

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

        String s1 = "java";
        String s2 = "JaVA";

        //문자열 s1, s2를 비교( 문자열 내용비교 ) 하시오. ★★★★★
        System.out.println("s1.equals(s2) = " + s1.contentEquals(s2)); // false : 대소문자 비교하기에~!
        //"java".equals( "JaVA" ) 사용가능

        //대소문자 구분없이 s1과 s2철자를 비교하시오
        System.out.println( "대문자변환" + s1.toUpperCase() );
        System.out.println( "소문자변환" + s2.toLowerCase() );

        System.out.println("전체 소문자(s1 s2) 변경 후 비교 = " + s1.toLowerCase().equals(s2.toLowerCase()));

        //문제) str문자열 안의 있는 숫자의 갯수를 화면에 출력하시오.
        //아스키 코드값  = 0은 48, a는 97 A는 65
        String str = "Java3Pro7gra9mm0ing"; // 화면에 '4' 출력


        int count = 0;
        System.out.println("str문자열길이( 문갯수 ) : " + str.length());
        for( int i = 0; i < str.length(); i++ )
        {
            char ch = str.charAt(i);
            if( ch > 47 && ch <60 ) //혹은 '0' '9'랑 비교해도 가능하다.
            {
                //숫자로 구성된 문자라면 
                count++;
                System.out.print(ch);
                if(i < str.length())
                System.out.print(", ");
            }
        }
        System.out.println("갯수 : " + count);

    }
}
궁금상자
    - 갑자기 든 생각인데 메모리 주소 출력 받은걸로 입력도 가능할까?

    - 하나의 for문안에 변수 2개

    - 로또 하 면서 봤는데 
    for( int i = dex - 1; i > -1; i--)는 되고 for( int i = dex - 1; i == 0; i--)은 안되네?
        바보야 i == 0... 조건이 아니야...
    - 왜 0부터 5까지 배열을 Arrays.sort(lotto, 0, 6); 하면 되고 Arrays.sort(lotto, 0, 5); 하면 안되지?
        선생님이 알려주심 이상 미만의 범위라서 그럼..~!
    - String과 StringBuffer의 차이
        고정일땐 String 가변일 땐 StringBuffer???

190118_Day9 복습, 삼항연산자, 클래스 객체 비교, 오토박싱 언박싱


//3조 발표 후 ~! 스위치문의 간결함!
package SwitchTest;

public class SwitchTest 
{
    public static void main(String[] args)
    {
        final int SEARCH = 1;
        final int INCREMENT = 2;
        final int DECREMENT = 3;
        final int EXIT = 4; // 상수형 final 변수라 대문자 변수명

        int su = 1;

        switch (su) {
            case SEARCH : System.out.println(" 검색 "); break; // case 뒤에 변수는 못넣고 상수만 넣을 수 있다.
            case INCREMENT : System.out.println(" 증가 "); break; 
            case DECREMENT : System.out.println(" 감소 "); break;
            case EXIT : System.out.println(" 종료 "); break;
        default:
            break;
        }
    } //main
}

복습

  • 배열

    • 한개의 변수명에 여러 개의 데이터를 저장하기 위해! 단, 데이터들은 같은 자료형

    • 통신할때, 데이터 관리가 매우 편해진다! 변수명 하나만 건내면 안에 내용 열개 백개를 보낼 수 있음

    • 여러 개의 데이터를 변수명 한 개를 사용해 전달, 배열 인덱스 사용 =>> for문 사용 : 전체 데이터를 검색!

    • 형식

      1. 배열선언과 초기화! =>> 프로그램내에 확정된 데이터가 있을 때 사용

        • 자료형 [] 배열명 = {value_list};
      //자료형 [] 배열명 = { 데이터1, 데이터2, 데이터3 };
      int [] nums = { 100, 200, 300 };
      // ㅁㅁㅁ 방을 만들고 그 안에 100, 200, 300을 넣어줌
      // 번지는 nums[0] nums[1] nums[2]
      1. 배열 객체 생성 =>> 프로그램 생성 중 데이터 입력

        • 자료형 [] 배열명 = new 자료형 [배열 크기] //형식은 꼭 외워줘!
      int [] nums = new int [3];
      nums[0] = 10;
      nums[1] = 20;
      nums[2] = 30;
      1. 2차원 배열 객체 생성

        • 자료형 [] [] 배열명 = new 자려형 [행크기] [열크기];
      int [][] nums = new int [3][2]; //3*2 : 6개의 정수데이터 입력 준비
      num[0][0] = 10;
      num[0][1] = 20;
      
      num[1][0] = 30;
      num[1][1] = 40;
      
      num[2][0] = 50;
      num[2][1] = 60;
    10 20
    30 40
    50 60

    java
    int [][] nums = new int [3][]; //가변길이열
    //ㅁㅁ nums[0] = new int[2];
    //ㅁㅁㅁ nums[1] = new int[3];
    //ㅁ num[2] = new int[1];

  • newA();

    • 100 + 200
    • new A().hello();
  • A a = new A();
    • 변수 su + 200
    • a.hello();
  • A [] aa = new A[5];
    • 배열 su[0] + 200;
    • aa[0] = a;
    • aa[0].hello();

어제 미션

//mission 내가 푼것
package mission;

public class Mission0417
{
    public static void main(String[] args)
    {
        int su[] = { 1, 2, 3, 4, 5};
        // 배열 크기 (su.length) =>> 5

        System.out.println("================<1번>===============");
        for( int i = 0; i < su.length; i++ )
        {
            System.out.print(su[i] + "\t");
        }
        System.out.println();
        System.out.println("================<2번>===============");
        for( int i = su.length - 1 ; i >= 0; i-- )
        {
            System.out.print(su[i] + "\t");
        }
        System.out.println();
        System.out.println("================<3번>===============");

        int su2[][] = { { 1 }, { 1, 2 }, { 1, 2, 3 } };
        for( int i = 0; i < su2.length; i++)
        {
            for( int j = 0; j <= su2[i].length - 1; j++)
            {
                System.out.println("su[ " + i + " ] [ " + j + " ] = " + su2[i][j]);
            }
        }

        System.out.println();
        System.out.println("================<4번>===============");

        int su3[] = {5, 5, 5, 5, 5}; 
        for ( int i = 0; i < su.length; i ++)
        {
            su3[i] = su[i];
        }
        System.out.println(su[2]);
        //이거 원본도 한번 출력해 보자!

        System.out.println();
        System.out.println("================<5번>===============");

        int temp;
        temp = su[0];
        su[0] = su[4];
        su[4] = temp;

        temp = su[1];
        su[1] = su[3];
        su[3] = temp;

        temp = su[0];
        for (int i = 0; i < su.length; i++)
        {
            System.out.print(su[i] + "\t");
        }


        System.out.println();
        System.out.println("================<6번>===============");

        temp = su[0];
        su[0] = su[4];
        su[4] = temp;

        temp = su[1];
        su[1] = su[3];
        su[3] = temp;

        temp = su[0];
        for (int i = 1; i < su.length; i+=2)
        {
            System.out.print(i+ "번지" + "\t");
        }

        System.out.println();
        System.out.println("================<7번>===============");

        temp = su[0];
        for (int i = 0; i < su.length; i+=2)
        {
            System.out.print(su[i] + "\t");
        }
    }
}
//선생님 해설
//mission
package MissionA;

class A
{
    void hello()
    {
        System.out.println("안녕");
    }
}

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

        int su[] = { 1, 2, 3, 4, 5, 60};
        // 배열 크기 (su.length) =>> 6

        A a = new A();
        a.hello();
        a.hello();
        System.out.println("=================");

        new A().hello();
        new A().hello();
        System.out.println("=================");





        A []arr = new A[3];
        //A [] arr = {null, null, null};
        arr[1] = new A();
        //A [] arr = {null, new A(), null};

//        arr[0].hello(); 아직 arr[0]이 할당 못받았다. NullPinterException 발생
        arr[1].hello();
        System.out.println( "arr 배열 크기 : " + arr.length );

//      int []su = { 1, 2, 3, 4, 5 };
        //인덱스               0  1  2  3  4

        //arr.length ? =>> 0, 3
        System.out.println("\n===============");
        System.out.println("문제 1");

        for (int i = 0; i < su.length; i++) 
        {
            System.out.print( su[i] );
            if(i < 4)System.out.print(", ");
        }

        System.out.println("\n===============");
        System.out.println("문제 2");

        for (int i = su.length-1 ; i > -1; i--) 
        {
            System.out.print( su[i] );
            if(i>0)System.out.print(", ");
        }        

        System.out.println("\n===============");
        System.out.println("문제 3");
        //2차원 배열을 다중for문을 통해 출력
        //행              0        1           2
        int su2[][] = { { 1 }, { 1, 2 }, { 1, 2, 3} };
        //열              0      0   1     0   1  2
        for( int i = 0; i < su2.length; i++ ) // 기준 : 행 인덱스
        {
            for( int j = 0; j < su2[i].length ; j ++ ) //각 행의 열 인덱스
            {
                System.out.println("su2[" + i + "][" + 0 + "]번지 = " + su2[i][j]);
            }
        }

        System.out.println("\n===============");
        System.out.println("문제 4");

        int su3[] = new int[ su.length ]; // new int[5]


        su3 = su; // su3과 su는 참조변수이다.(속성변수가 아닌) , 이는 메모리 값의 주소! 주소 값을 전해준다.
        //su3[2] = 33; // 이렇게 해버리면 원본까지 바뀌어 버린다.

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

        System.out.println("원본출력");
        for (int i = 0; i < su3.length; i++)
        {
            System.out.println("su[" + i + "] = " + su[i]);
        }

        //원본까지 바뀌지 않기 위해
        for (int i = 0; i < su.length; i++)
        {
            su3[i] = su[i];
            System.out.print(su3[i]);
            if(i <4 )System.out.print(", ");
        }
        /*출력값
        문제4)
su3[0]=12
su3[1]=2
su3[2]=33
su3[3]=4
su3[4]=5
su3[5]=65
===원본su배열출력===
su[0]=12
su[1]=2
su[2]=3
su[3]=4
su[4]=5
su[5]=65
        */
        System.out.println("\n===============");
        System.out.println("문제 5");

        //데이터 교환
        //int j = 4; //교환할 오른 쪽 데이터 인덱스 4 3 
        int temp;
        for(int i = 0, j = su.length - 1 ; i < su.length/2; i++, j--) //교환할 왼쪽 데이터 인덱스 0, 1
        {
            temp = su[i];
            su[i] = su[j];
            su[j] = temp;

            //j--;
        }

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

        /*
        문제5)
su[0]=65
su[1]=5
su[2]=4
su[3]=3
su[4]=2
su[5]=12

        */
        System.out.println("\n===============");
        System.out.println("문제 6 홀수번지 출력하기");
        for (int i = 0; i < su.length; i++)
        {
            if(i%2==1)//홀수번지 (==인덱스) 조건
                System.out.println( "su["+i+"] = " + su[i]);
        }

        System.out.println("\n===============");
        System.out.println("문제 7 홀수번지 출력하기");
        for (int i = 0; i < su.length; i++)
        {
            if(su[i]%2==1)//홀수데이터값 조건
                System.out.println( "su["+i+"] = " + su[i]);
        }


    }//main    
}

<삼항연산자>

  • 형식

    조건식 ? A : B
    (조건식) ? A : B
    => 조건식의 결과가 true였을 때 A리턴, 결과가 false였을 대 B리턴
  • 사용 예)

    boolean b =  (3<4)  ?  true  : false;
    //  ==> b변수에 true 저장
    
    int su=1;
    String gender =  su%2!=0  ?  "남자"  : "여자";
    //  ==> gender변수에 "남자" 저장
    
    int su2 =  ('남' == '여')  ?  100  : 300;
    //  ==> su2변수에 300 저장

<클래스 객체 비교>

  • 클래스 참조변수 == 클래스 참조변수2 =>> 메모리 주소 비교

    A a1 = new A(); 
    A a2 = new A();
    System.out.println(a1 == a2)
      //결과값 false : 서로 다른 메모리 주소
    
    a2 = a1 //a1이 갖은 주소를 a2에 전달
    System.out.println(a1 == a2)
      //결과값 true : 서로 같은 메모리 주소
  • 위와 비교해서 참고

    • 속성변수1 == 속성변수 =>> 데이터 값 비교!
    int su1 = 30;
    int su2 = 30;
    System.out.println(su1==su2)
    //결과값 true : 값은 값을 갖는다.
int su1; // 속성변수 (기본 자료형으로 선언된 변수)
su1 = 100;
su1.~ (x)

Integer su2; // 참조변수!! (데이터의 위치는 메모리이고 그 메모리의 주소를 담는 변수!)
su2 = new Integer(100);
su2.~ (o)

오토박싱 언박싱

  • JDK 5버전 이후 지원
  • int, double과 같은 기본형 자료형의 포장 클래스가 있어, 기본형을 객체로 다루어야 할 경우에 사용 가능
  • 포장하는 클래스, 기본 자료형을 포장한다!
  • 자바의 모든것은 객체?! =>> 객체가 아닌것들도 존재 =>> 기본 자료형(빈번한 연산을 하기 위해 높은 성능을 위해 객체화 하지 않은 듯?!)
  • 객체가 아니어서 컬렉션 또는 다형성 제네릭 이용시에 불편!
  • 그래서 래퍼 클래스를 사용한다!
  • 기본자료형과 래퍼간 == 연산과 equals연산 모두 성립.
  • 하지만 래퍼와 래퍼 사이는 equals 성립, == 성립 안함. 단 대소 비교 > < 가능
int su3 = new Integer(300);
Integer su4 = 300;
  • 기본자료형 래퍼클래스 (위치: 기본패키지 java.lang)
    byte —-> Byte
    short —-> Short
    int —-> Integer (정수와 관련된 속성,메소드를 지원하는 클래스)
    long —-> Long
    float —-> Float
    double —-> Double
    char —-> Character
    boolean —-> Boolean

  • 생성자는 위와 같이 해당하는 기본형을 줄 수도 있고 문자열로 줄 수도 있다. 문자열로 주는 경우 형식에 맞아야 함

  • 근데 래퍼클래스 사용시 참조형끼리 연산 불가… 다시 자료형으로 변환하여 연산…

  • 그래서 오토박싱과 언박싱이 등장!

  • 오토박싱은 기본자료형을 래퍼클래스로 감싸주지 않아도 박싱

    Integer k = 2; // 내부적 동작 Integer a = new Integer(2);
    Object L = 2 // Object o = new Integer(2) 로 동작, 다형성
  • 언박싱은 기본자료형으로 변환 안해도 포장을 풀어줌

    Integer k = new Integer(2);
    int i = a; // 내부적으로 int i = a.intValue(); 로 동작
  • 박싱이라는게 기본형->참조형 변환

  • 언박싱은 참조형-> 기본형 변환

  • 래퍼클래스 이용하여 문자열을 기본 자료형으로 변환 가능, 문자열을 래퍼클래스로 변환 가능

궁금상자
- 배열은 같은 자료형으로 모여야 하는데 , 그럼 2차원 배열에서 안에 배열은 스트링 밖에 배열은 숫자 이렇게도 가능할까?

- boolean 기본 값 false? char 는 '/u0000' 맞나?
for(int i = 0; i < su.length; i++)
    {
        for ( int j = 0; j < i; j++)
        {
            if(su[i] == su[j])
            {
                su[j]--;
                break;
            }   
        }
    }

190417_Day8 라인단위 입력, 클래스 객체 생성, 배열, 2차원 배열

복습

추상클래스

  • 메소드 구현을 상속받은 클래스에 강제한다.

  • 자식클래스들을 제어할 목적

  • 자식클래스들의 특징을 모아놓은 클래스

  • 추상 클래스는 객체생성 new 불가 => 자식클래스 객체생성

  • 형식

  • abstract class 클래스명
    {
      int su; // 변수선언;
      명시적 생성자;
      void hello() {} // 구현(정의)메소드;
      abstract void print(); // 선언 메소드, 이름만 짓고 , 자식클래스에서 기능넣기!, 얘는 접근제한자 안 적어도 public
    //*오버라이딩, 상속시에 자식 클래스는 반드시 부모클래스의 접근제한보다 같거다 커야 한다.   
    }
  • 클래스 사용 => 객체생성해서 사용

    class A{ void hello(){} }
    //==
    A a = new A();
    a.hello();
  • 인터페이스 사용 => 클래스에 구현(implements)해서 사용

    interface B {void hello(); }
    //==
    class a implements B { void hello(){} }
  • 추상클래스 사용 => 자식클래스 객체 생성해서 사용

    class Child extends Parent { void print() {} }
    //==
    A a = new A();
    a.hello();

메소드 호출

  • public void my()
    {
      m1( ); // 1. 메소드 호출
    
      m2(); // 에러 발생
      m2( 500 ); // 3. 500을 넣어서 매개변수 통해 전달,데이터 혹은 데이터를 담은 변수안의 데이터를 줘야 한다. 
      int num = m3( ); //6. 반환 받은 값 800을 num을 선언하며 초기화
    }
    
    //==
    void m1( ) // 이름을 불러주세요
    {
      문장1;
      문장2;
      문장3;
    } // 2. 반환
    
    void m2( int su ) // 정수 데이터 주세요
    {
    
    }// 4. 반환
    
    int m3( ) // 결과값을 정수로 드릴게요
    {
      return 800; //5. 반환
    }
//이거 좀 많이 헷갈리네...
class Parent{ }
class Child extends Parent{ }
//-------
//<메소드 정의>
pulic void  hello( Child c ) 
{

}
public void goodBye( Parent p ) 
{
    //Parent p = new Child(); 대체 가능
}
//-------
//<메소드 호출>
hello(new Child());

//위와 같은 표현
Child cc = new Child();
    hello( cc );

hello(new Parent( ) ); //? 안됩니다. 자식객체에 부모객체가 들어갈 수 없다!
//--------
goodBye(new Parent); // 가능

Parent pp = new Parent();
goodBye( pp );

goodBye( new Child( ) ); //가능!


//--------
void a(String greeting)
{

}

String b(int su)
{
    return "안녕하세요";
}

int c()
{
   return 500; 
}

//--------
a( b( c( ) ) ); //이런식으로도 가능하다! c-> b-> a 순으로 실행됨 
//<--실행순서---
//--------

  • <라인단위입력>
    클래스 BufferedReader –>> 메소드 readLine()
    API문서 정보 =>> BufferedReader
    A a = new A();
    Reader r = new Reader(); =>>(x)=>> 추상클래스 : 자식 ==> InputStreamReader

    InputStreamReader is = System.in;
    Reader r = new InputStreamReader(); =>>(o)
    BufferedReader br = new BufferedReader( r );
    이렇게 3줄이 나와야 br.readLine(); 사용가능 줄을 구분자로 하는 text입력

    근데 is 나 r은 한번 쓰고 다시는 안쓰는데… 굳이 변수지정?!
    BufferedReader br = new BufferedReader( new InpuStreamReader( System.in ) );

  • 클래스 객체 생성

    • 멤버 필드, 멤버 메소드들에 대한 메모리 할당

      1. 동적 메모리 할당

        • 사용안하는 객체에 대해서 가비지 컬렉터가 자동 소멸 관리

        • 키워드 : new

        • 사용법 : 참조변수를 통해 참조

      A a = new A();
      a.hello();
      1. 정적 메모리 할당

        • 자주 사용되는 필드, 메소드에 대해 정의
        • 객체들간의 통신에 사용 ( 공뷰 데이터를 표현 )
        • 키워드 : static
        • 사용법 : 클래스 명으로 참조
        • 클래스명.필드명 클래스명.메소드명(); =>> 클래스변수, 클래스메소드
      class B
      {
       static int su = 100; //static public == public static 이다!
       public static void goodBye(){}
      }
      
      //====================================
      //<길동개발자>          <라임개발자>
      //B.goodBye();         B.goodBye();
      //Syso(B.su); 100출력        
      // B.su++;
      //                     Syso(B.su); 101출력!
      //System.out.println();
      //out은 필드 .println();은 메소드
      public class System
      {
       static PrintStream out;
      }
//어제 mission 풀이
/*
*
**
***
****
*/

public class StarTest 
{
    public static void main(String[] args) 
    {
        for(int i = 1; i < 5; i ++)
        {
            for(int j = 1; j <= i  ; j++)
            {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}
//========================== 거꾸로

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

        for(int i = 4; i > 0; i--)
        {
            for(int j = 1; j <= i; j++)
            System.out.print("*");

            System.out.println();
        }
    }
}

배열

  • 자료형이 동일한 데이터들에 같은(한개의) 변수명을 정의한 자료들의 집합.

    • 자료형이 동인한 데이터들 => 조건

    • 같은(한개의) 변수명을 정의=>특성

    • 자료들의 집합 => 정의

    int su; -> 한 개의 정수를 저장할 준비

    int []su2; ->여러개의 정수를 저장할 준비

    • 서로 데이터들을 구분하기 위해 번지를 사용.

    • 시작번지는 0번지, 1씩 증가하는 번지를 가짐

    • 배열의 크기가 정해지면 인덱스를 벗어나는 참조를 하면 안됨.

    int [] su3 = { 10, 20, 30 };

    번지 인덱스 = su3[0] su3[1] su3[2]

    배열의 크기 ( 요소 갯수 ) : 3 ( 인덱스 0~2 )

  • <5000 데이터 출력>

    System.out.println(5000);
    
    int su = 5000;
    System.out.println(su);
    
    int []suArr = { 5000 };
    System.out.println( suArr[0] );
  • 배열의 크기 ( 배열의 요소 갯수 ) 를 구하는 속성 : 배엷명.length (배열은 객체다)

  • 배열선언시 []는 변수명 앞에 또는 뒤에 붙여도 상관이 없다.

    int []su;

    int su[];

    .

    int i;

    int j;

    int k;

    ===>> int i,j,k;

  • 차이점)

    int su1[],su2; =>> su1은 정수배열, su2는 정수

    int [] su1, su2; =>> su1, su2 둘다 정수배열

  • 참고)

    class A
    {
        int i; // 기본값 존재
    
        void hello()
    {
    int j; // 지역변수 기본값 존재 X
    System.out.println(i); // 출력? 0
    
    System.out.println(j); // 출력? 초기화하지 않았다는 에러 발생
        j = 0;
        System.out.println(j); // 출력? 0
    
      int a,b,c = 0;
      System.out.println(b); // 출력? 에러 발생, c만 0으로 초기화 된거야!, 방지하려면 int a = 1, b = 2, c =0; 이렇게 각각 초기화까지 해줘야 한다!
    }//hello
    }
  • <배열형식>

    1. 자료형 [ ] 배열명 = { 데이터List( 콤마로 구분되는 데이터 ) };

      =>> 배열 선언과 동시에 데이터를 초기화. ( 이미 데이터가 확정되었을 때 사용 )

      =>> 주의 : 배열 선언과 데이터 초기화하는 부분을 따로 작성할 수 없음!

      int [] su; // 배열선언
      su = {1,2,3,4,5}; // 배열초기화 (X)
      
      //===
      
      int [] su = { 1, 2, 3, 4, 5 } // 선언과 동시에 초기화 (o)
      
      //===
      A a = new A();
      a []su = { a, newA(), newA() };
    2. 자료형 [ ] 배열명 = new 자료형 [배열크기]; // 배열 객체 생성식 : 암기!

      =>> 프로그램 실행 도중 데이터 값을 입력, 변경할 때 주로 사용

      ​ =>> 데이터가 정해지지 않고 앞으로 입력받을 데이터들이 저장될 방(공간)만 준비

      ==>> 배열선언과 데이터 초기화하는 부분을 따로 작성하는 것이 가능

      ==>> 배열 크기 []는 반드시 자료형 뒤에 위치해야 함

      ==>> 배열크기에 정수값이 반드시 입력되어야 함.

        int []su; // 배열선언
      
        su = new int[5]; //배열초기화 (su 배열변수에 5개의 정수를 입력 받겠음!)
      
      // 이는 이렇게 써 된다.
      int [] su = new int [5];
      
      // 데이터 입력 
      su[0] = 11;
      su[1] = 22;
      su[2] = 33;
      su[3] = 44;
      su[4] = 55;
      
      su[5] = 66; // 얜 인덱스를 벗어났으므로 에러~!  
      // 배열 객체생성( 위의 2번 ) 을 하게 되면 그 위치에 상관없이 각방에는 초기값이 부여됨
      // ( 멤버변수 처럼 각 자료형의 기본값이 입력됨 )
      
public class ArrayTest 
{
    public static void main(String[] args) 
    {
        //1. 배열 선언과 초기화
//      int []su;
//      su = { 1, 2, 3, 4, 5 }; 에러 발생 : 반드시 선언과 동시에 초기화를 함게 기술할 것!

        int []su = { 1, 2, 3, 4, 5 }; // 이렇게 선언과 동시에 초기화 할 것! { su[0], su[1], su[2], su[3], su[4] }
        int su1[] = { 1, 2, 3, 4, 5 };

        System.out.println( "su[0]번지 = " + su[0]);
        System.out.println( "su[1]번지 = " + su[1]);
        System.out.println( "su[2]번지 = " + su[2]);
        System.out.println( "su[3]번지 = " + su[3]);
        System.out.println( "su[4]번지 = " + su[4]);
        // System.out.println( "su[5]번지 = " + su[5]); 에러발생 인덱스를 벗어남!


        System.out.println("=====================================");
        System.out.println("배열의 크기 ( 요소갯수 ) " + su.length);

        for(int i = 0; i < su.length; i++ ) 
        {
            //배열의 인덱스 표현 ( 0, 4)
            System.out.println("su[ "+ i + " ]번지 = " + su[i]);
        }
    }
}
package Rand;

import java.util.Random;

public class RandArrayTest
{       
        int []su; // null 값이 들어감
        Random r;

        public RandArrayTest() 
        {
            su = new int[5]; // [0]번지 ~ [4]번지 생성
            r = new Random();
        }

        public void inputArray() 
        {
            for (int i = 0; i < su.length; i++)
            {
                //랜덤(임의의 난수) 수를 발생해서 배열안에 입력
                //su[i] = (int)( Math.random() * 100 ); //0.0 ~ 0.999999999... * 100 을 다섯번 호출, 캐스팅이 우선순위라 괄호 하기
                //      ----- 캐스팅 연산자 (형변환 연산자) 
                su[i] = r.nextInt(1000) + 1; // 0~999,  + 1 : 0~1000
            }

        }
        public void printArray() 
        {
            for(int i = 0; i < su.length; i++)
            {
                System.out.println("su[ " + i + " ] = " + su[i] );
            }
        }
        public void sortArray() {}

        public static void main(String[] args) 
        {
            RandArrayTest rat = new RandArrayTest();
            rat.inputArray();
            rat.printArray(); // 배열값 출력
        }

}
/*
su[ 0 ] = 804
su[ 1 ] = 782
su[ 2 ] = 632
su[ 3 ] = 57
su[ 4 ] = 375
*/
//swap
package Rand;

public class SwapTest
{
    public static void main(String[] args)
    {
        int su1 = 50;
        int su2 = 30;

        int temp = su1; //임시변수 temp = 50;
        //교환식
        su1 = su2; // su1 = 30;
        su2 = temp; // su2 = 50; 

        System.out.println( "su 1 = " + su1 ); //30
        System.out.println( "su 2 = " + su2 ); //50

        //---------------------

        int []arr = { 300, 100 };

        //배열의 값 변경

        temp   = arr[0];
        arr[0] = arr[1];
        arr[1] = temp;

        System.out.println( "arr[0] = " + arr[0] );
        System.out.println( "arr[1] = " + arr[1] );

    }
}
package Rand;

import java.util.Random;

public class RandArrayTest
{       
        int []su; // null 값이 들어감
        Random r;

        public RandArrayTest() 
        {
            su = new int[5]; // [0]번지 ~ [4]번지 생성
            r = new Random();
        }

        public void inputArray() 
        {
            for (int i = 0; i < su.length; i++)
            {
                //랜덤(임의의 난수) 수를 발생해서 배열안에 입력
                //su[i] = (int)( Math.random() * 100 ); //0.0 ~ 0.999999999... * 100 을 다섯번 호출, 캐스팅이 우선순위라 괄호 하기
                //      ----- 캐스팅 연산자 (형변환 연산자) 
                su[i] = r.nextInt(1000) + 1; // 0~999,  + 1 : 0~1000
            }

        }
        public void printArray() 
        {
            for(int i = 0; i < su.length; i++)
            {
                System.out.println("su[ " + i + " ] = " + su[i] );
            }
        }
        public void sortArray() 
        {
            int temp;
            for(int i = 0; i < 4; i++) // 비교할 왼쪽(기준) 데이터 0 1 2 3 4
            {
                for(int j = i + 1; j < 5; j++) // 비교 오른쪽 데이터 1, 2, 3, 4     2,3,4       3,4     4
                {
                    if(su[i] > su[j]) //정렬조건 오름차순 ex) 정렬 12345, abcde, 가나다라마
                    {
                        //i와 j는 배열의 번지수를 표현
                        temp = su[i];
                        su[i] = su[j];
                        su[j] = temp;
                    }

                }
            }

        }

        public static void main(String[] args) 
        {
            RandArrayTest rat = new RandArrayTest();
            rat.inputArray(); //난수 데이터를 배열에 입력
            rat.sortArray(); //데이터 정렬(오름차순)
            rat.printArray(); // 배열값 출력
        }

}

<2차원배열>

  • 실제 저장은 1차원 배열과 같으나 논리적으로 데이터를 행과 열의 형태로 저장한다고 생각, 표현.

  • 행 사이즈는 반드시 기술해야 하며, 열 사이즈는 생략하는것이 가능

    //배열선언
    int [][]su;
    int su[][];
    int []su[]; //대괄호의 위치는 상관이 없다.
    //            ----0행----    ----1행----
    int [][]su = { { 1, 2, 3 }, { 4, 5, 6 } };
    //                -------     --------
    //                열:0,1,2     열:0,1,2
    
    System.out.println(su[0][2]); //0행 2열 데이터 =>> 3
    System.out.println(su[1][1]); //1행 1열 데이터 =>> 5
    
    su.length // 행의 갯수 => 2 
    su[0].length //== 0행의 열의 갯수 =>> 3
    su[1].length //== 1행의 열의 갯수 =>> 3
    
    for( int i = 0; i < su.length; i++ )  //기준(행) : 행의 인덱스 표현
    {
      for( int j = 0; j < su[i].length; j++ ) //각 행의 열 인덱스 : 0, 1, 2
      {
          System.out.prinln( su[i][j] ); // su i행 j열
      }
    }
    public static void main(String[] args) 
    {
      RandArrayTest rat = new RandArrayTest();
      rat.inputArray(); //난수 데이터를 배열에 입력
      rat.sortArray(); //데이터 정렬(오름차순)
      rat.printArray(); // 배열값 출력
    
      int [][]su2 = { { 1, 2, 3 }, { 4, 5, 6 } };
    
      System.out.println( "su2배열의 행 갯수" + su2.length );
      System.out.println( "su2배열 첫번째 행의 열(데이터) 갯수 " + su2[0].length );
      System.out.println( "su2배열 두번째 행의 열(데이터) 갯수 " + su2[1].length );
    
      //전체 데이터 조회
      for(int i = 0; i < su2.length; i++)
      {
          for(int j = 0; j < su2[i].length; j++ )
          {
              System.out.println("su2[" + i + "][" + j + "] = " + su2[i][j]);
          }
      }
    }
    
    /*
    su2배열의 행 갯수2
    su2배열 첫번째 행의 열(데이터) 갯수 3
    su2배열 두번째 행의 열(데이터) 갯수 3
    su2[0][0] = 1
    su2[0][1] = 2
    su2[0][2] = 3
    su2[1][0] = 4
    su2[1][1] = 5
    su2[1][2] = 6
    */
    //mission
    
    package mission;
    
    public class Mission0417
    {
    public static void main(String[] args)
    {
        int su[] = { 1, 2, 3, 4, 5};
        System.out.println("================<1번>===============");
        for( int i = 0; i < su.length; i++ )
        {
            System.out.print(su[i] + "\t");
        }
        System.out.println();
        System.out.println("================<2번>===============");
        for( int i = su.length - 1 ; i >= 0; i-- )
        {
            System.out.print(su[i] + "\t");
        }
        System.out.println();
        System.out.println("================<3번>===============");
    
        int su2[][] = { { 1 }, { 1, 2 }, { 1, 2, 3 } };
        for( int i = 0; i < su2.length; i++)
        {
            for( int j = 0; j <= su2[i].length - 1; j++)
            {
                System.out.println("su[ " + i + " ] [ " + j + " ] = " + su2[i][j]);
            }
        }
    
        System.out.println();
        System.out.println("================<4번>===============");
    
        int su3[] = {5, 5, 5, 5, 5}; 
        for ( int i = 0; i < su.length; i ++)
        {
            su3[i] = su[i];
        }
        System.out.println(su[2]);
    
    
        System.out.println();
        System.out.println("================<5번>===============");
    
        int temp;
        temp = su[0];
        su[0] = su[4];
        su[4] = temp;
    
        temp = su[1];
        su[1] = su[3];
        su[3] = temp;
    
        temp = su[0];
        for (int i = 0; i < su.length; i++)
        {
            System.out.print(su[i] + "\t");
        }
    
    
        System.out.println();
        System.out.println("================<6번>===============");
    
        temp = su[0];
        su[0] = su[4];
        su[4] = temp;
    
        temp = su[1];
        su[1] = su[3];
        su[3] = temp;
    
        temp = su[0];
        for (int i = 1; i < su.length; i+=2)
        {
            System.out.print(i+ "번지" + "\t");
        }
    
        System.out.println();
        System.out.println("================<7번>===============");
    
        temp = su[0];
        for (int i = 0; i < su.length; i+=2)
        {
            System.out.print(su[i] + "\t");
        }
    }
    
    }
    /*
    ================<1번>===============
    1 2   3   4   5   
    ================<2번>===============
    5 4   3   2   1   
    ================<3번>===============
    su[ 0 ] [ 0 ] = 1
    su[ 1 ] [ 0 ] = 1
    su[ 1 ] [ 1 ] = 2
    su[ 2 ] [ 0 ] = 1
    su[ 2 ] [ 1 ] = 2
    su[ 2 ] [ 2 ] = 3
    
    ================<4번>===============
    3
    
    ================<5번>===============
    5 4   3   2   1   
    ================<6번>===============
    1번지   3번지 
    ================<7번>===============
    1 3   5   
    */
궁금상자
- 동적, 정적 메모리가 변화 있고 없고 차이가 아니었나보네? 알아보자!

- 

190415 Day7 this, interface, mission, 배열, 자바빈즈, 추상클래스

복습

System.out.println(); 에서 out은 필드인데 어떻게 메소드인 println()을 포함하고 있지?

  • out은 PrintSteam이라는 메소드로 정의되어 있음 PrintStream out; 이렇게

명시하는 this

  • this는 보통 생략하지만 명시할 때도 있다. 생성자가 두개 있을 때

  • public class Abc
    {
      int su;
    
      public Abc()
      {
    
      }
    
      public Abc(int su)
      {
          su = su;
      }
    
      public void hello()
      {
    
      }
    }
    
    /*
    객체생성1
    abc a = new Abc();
    System.out.println(a.su);
    -> 이렇게 하면 0 출력됨
    
    객체생성2
    Abc a = new Abc(500); // 2번생성자 호출
    System.out.println(a.su);
    -> 이렇게 하면 0이 나옴, su = su는 지역변수에 500을 넣어라가 되어버림
    -> 500이 나오게끔 하고 싶다면 멤버와 지역변수의 이름을 다르게 한다 -> 하지만 이런 경우는 많이 없다. 연관성 주기 위해 이름 같게 함 보통, 그래서 this.su = su 이렇게 명시하면 된다.
    -> Abc(){this(100);} 을 넣어주면 Abc(int su)에 su 값에 100을 넣어주게 된다. 
    
    */

interface

  • 객체를 연결해주는 매개체, 메뉴판 같은, 손님과 주방장을 이어주는!

  • //내가 만든 것
    
    class A implements Common
    {
      void hello()
      {
          System.out.print("신짜오")
      }
    }
    
    //이미 Commmon에는 hello()가 정의되어있다.
    /*
    Common c;
    c = new A();
    c.hello();
    */
    
    class implements Common
    {
      void hello()
      {
          System.out.print("봉쥬르");
      }
    }
    
    /*
    c = new B();
    c.hello();
    */
    
    Common이라는 interface를 통해서 A와 B 클래스를 필요할때마다 쓴다
    느슨한 관계!

mission

package com.encore.$0415.misson;

import java.io.IOException;

/*
 * 기능정의
 * -단입력
 *  int inputDan ()
 * {
 *  int dan = read() 또는 readLine() 을 사용해서 받기 //그리고 단출력에 전달해야 함, return 타입 통해
 * }
 * 
 * -단출력
 *  void outputDan () 
 * {
 *  //전달받은 dan에 대한 출력
 * }
 * -계속여부
 *  char continueDan () 
 * {
 *  read() 또는 readLine()
 * }
 */

public class Gugudan 
{
    //public int dan;//=0
    //public char continuedan;//='\u0000'


    int inputDan() throws IOException
    {
        System.out.println("원하시는 단을 입력해주세요");
        int dan = System.in.read() - 48;
        System.in.read();
        System.in.read();
        return dan;

    }

    void outputDan(int dan)
    {
        System.out.println(dan + "단 구구단 출력");
        for (int i = 1; i <10; i++)
        {
            System.out.println(dan + "X" + i + " = " +  dan*i) ;
        }
    }

    char continueDan() throws IOException
    {
        System.out.println("계속하시겠습니까?");
        char continuedan = (char) (System.in.read());
        System.out.println(continuedan);
        System.in.read();
        System.in.read();
        return continuedan;

    }

}


//===

package com.encore.$0415.misson;

import java.io.IOException;

/*
 * main() 포함
 * 반복적인 실행을 할 것(while 또는 do~while 사용 하면 됨)
 * 이번은 while로 해보자!
 * 반복문 내에서 Gugudan클래스 안에 3개의 메소드가 있는데 3개의 메소드들을 적당히 호출.
 */

public class GugudanTest extends Gugudan
{

    public static void main( String[] args) throws IOException
    {
        Gugudan g = new Gugudan(); 


        System.out.println("구구단");

        int dan = g.inputDan();
        g.outputDan(dan);

//      
//      g.inputDan();
//      g.outputDan(dan);
//      g.continueDan();
//      

        while(g.continueDan() == 'y' )
        {
            dan = g.inputDan();
            g.outputDan(dan);
        }
            System.out.println("종료");
    }

}
//선생님이 설명해주시는 것
//MyTest.java

public class MyTest {

    public static void main(String[] args) {
        My my = new My();
        You you = new You();

        int su = my.juwon();
        you.lime(su);

    }

}
//My.java

public class My {

    int su; // 멤버변수, 필드 ==> 클래스내의 메소드들이 공유할 데이터

    public int juwon()
    {
        //발생되는 데이터
        su = 300;
        //발생된 데이터 주기 =>> 리턴
        return su;
    }




}

class You
{
    public void lime(int su)
    {
        System.out.println("su = " + su);
    }
}
package A0416;

public class MethodCallTest 
{
    public static void main(String[] args) {
        A a = new A();

        a.hello();

        //메인 메소드 실행 중 발생 데이터 : 100
        int su = 100;
        String name = "나길동";
        String name2 = "길라임";
        int age = 15;

        //m1()메소드에게 su를 전달
        a.m1(su);//메소드 호출 () 소괄호 안에 데이터를 표시
        a.m2(name); // 메소드 호출 시 ㅌ데이터를 전달 할 수 있다.

        //데이터 두개 : 15,"길라임" => m3에게 전달
        a.m3(name2, age);

        //String name2라는 변수는 m3에 전달되지 않음
        //name2가 담고 있는 데이터(value) "길라임"만 전달!

        //---------------
        int i = 10;
        int j = 20;
        int k = 30;
        // m4()메소드에게 정수값 10, 20, 30 전달!
        a.m4(i, j, k);


    } //main

}

//A.java
package A0416;

public class A {
    //메소드 정의!

    public void hello()
    {
        System.out.println("A클래스 안녕~!");
    }

    public void m1()
    {

    }

    public void m1(int su)
    {
        System.out.println("m1() : " + su );
    }

    public void m2(String name) 
    {
        //main()메소드에 a.m2("나길동"); 실행되면
        //m2()에서는 String name = "나길동";이 가장 먼저 실행되어집니다.
        System.out.println("m2() : " + name);
    }

    public void m3(String name2, int age) {
        System.out.println("m3() : " + name2 + ", " + age);

    }

    public void m4(int su1, int su2, int su3) {
        System.out.println(su1 + ", " + su2 + ", " + su3);

    }


}

배열

  • 데이터형이 동일한 자료에 같은 (하나의) 변수명을 정의한 자료들의 집합.

    ​ ——————-복수 데이터

  • 데이터형이 동일한 자료 ==>> 조건

  • 같은(하나의) 변수명을 정의 ==>> 특성

  • 자료들의 집합 ==>> 정의

  • -
11 22 33
ture false true
“길동” “라임” “주원”
‘j’ ‘a’ ‘v’

- int su1 =11; int su2 = 22; int3 =33;

  • int [ ] su = { 11, 22, 33 }; =>> su라는 배열변수에 복수 데이터를 대입!

  • 배열은 왜 쓸까?!

    • 그냥 나열하면 되는데…
    • 관리가 편하다!
    • but, 문제가 있다 구분이 안가… 그래서 구분을 만들었어!
    • 실제 {} 안에는 구분이 있음 {ㅁㅁㅁ} 이렇게!
    • 자바에서는 배열은 객체
    • su[]는 전체 데이터 su[0], su[1] , su[2] 는 각각의 데이터
    • 데이터를 구분하기 위해서 사용 =>> su라는 배열변수에 복수 데이터를 대입!
  • int su; =>> 한개의 데이터 입력

  • int []su; =>> 여러개의 데이터 입력 (배열)

  • boolean [ ] b = { true , false, true };

  • String [ ] str = { “길동”, “라임”, “주원” };
  • char []ch = { ‘j’, ‘a’, ‘v’, ‘a’ };

  • 데이터를 구분하기 위해서 번지를 사용

  • 시작번지는 항상 0번지부터 시작!
  • 첫번째 데이터 부터 인덱스(자동번호)가 부여
  • 인덱스는 0부터 시작해서 1부터 증가
  • 배열의 크기가 정해지면 인덱스를 벗어나는 참조를 하면 안됨
  • int [] su3 = {10, 20, 30};
  • 번지 =>> 0 1 2
  • System.out.println( su3[1] ); // 데이터 사용 (두번째 데이터 출력)
  • System.out.println( su3[3] ); // 하면 에러 발생 ArrayIndexOutOfBoundsException

  • for는 규칙적인 수 반복 할때, 배열과 친하다!


자바빈즈

  • 서로 관련성 있는 속성을 묶어주는 클래스(객체)

  • 사용하는 곳에 따라 VO(ValueObject) 또는 DTO(Data Transfer Object) 라는 이름을 사용하기도 함.

  • 사용하고자 하는 속성들을 규칙 약속함! - 개발자들끼리

  • 규칙)

    1. 속성데이터를 private하게 선언
    2. public 선언된 주고 받는 메소드 (get, set)를 정의

    ==========================================

    1. public한 기본생성자, 오버로딩 생성자를 정의 할 수 있다.
    2. 반드시 속성의 수와 일치하는 get, set이 정의되지 않아도 됩니다.
  • 참고)

    1. get으로 시작되는 메소드들 : 게터(getter)메소드
    2. set으로 시작하는 메소드들 : 세터(setter)메소드
    3. public한 기본생성자, 오버로딩생성자 정의 할 수 있다.
  • public class Person 
    { 
      private String name; 
      private int age; 
      private String job; 
    
      public Person(){}
        public Person (String name, int age, String job)
      {
          this.name = name;
          this.age = age;
          this.job = job;
      }
    
    
          public void setName(String name) //main에 있는 홍길동 받아옴
          {
              this.name = name;
          }
          public void setAge()
          {
              this.age = age;
          }
          public String getName()
          {
              return name; // this. 생략
          }
          public String getJob()
          {
              return job; // this. 생략
          }
    
    }
    //private 붙이면 쓰레긴데?!
    
    //===main===
    Person p = new Person();
    p.name = "홍길동"; //=>> 이름 정보 주기(설정) : 에러발생
    p.setName("홍길동") //=>> 실행 OK
    //system.out.println(p.name); //=>> 이름정보를 받기(얻기) private없다면 "홍길동 출력"
    System.out.println( p.getName() );
    //but, Person class에 private String name; 을 해버리면 에러가 난다!
  •  
  • public class Person { String name; int age; String job; }

    •  

alt + shift + s 통해서 getter setter 자동 생성!

ctrl + shift +enter 기본생성자 생성!

필드값도 생성하자!

1555387690155

매개변수와 get는 같지만 방향성이 조금 다른것일 뿐


추상클래스

  • 후손 class를 제어할 목적으로 사용.
  • 객체화 될 수 없는 클래스
  • 구현(정의)된 메소드와 선언된 메소드로 구성
  • 스스로 객체생성 불가 ( new 사용 X ), 후손class 객체생성(지식은 부모다)해서 사용
class 기본클래스
{
    //정의(구현)된 메소드
    void hello(){}
}

//---

class 추상클래스
{
    //선언된 메소드, 정의된 메소드
    void hello();
    void goodBye(){}
}

//---

interface 인터페이스
{
    //선언된 메소드만!
    void hello(){};
}
//추상 클래스 형식
abstract class 클래스명
{
    //필드선언
    public void hello(){}//구현된(정의된) 메소드
    abstract void print(): // 선언된 메소드(abstract 붙여줘야해)
}
  • 주의!
    • 선언된 메소드를 사용하는 경우 반드시 abstract 명시!
    • 만약 abstract 미기재시에는 에러 발생!
궁금상자
- 배열에서 시작은 0인데 바꿀 수 없나? 그리고 순서가 +1이 아니라 +2 씩 증가하게 할 수 없나?

- 배열은 타입이 같아야 하는데 만약 문자 숫자 배열 두개를 매번 교차로 출력하고 싶다면 그냥 for문 써서 하나씩 해야 하나?
    선생님이 설명해주심 바로,,ㅋㅋ 숫자를 문자로 형변환 후!

- super(); ? 빼도 된다구?

- 매개변수와 getter

- 자바 ioc?

190415_6일차 이클립스 설치, 접근지정(제한)자, 자기참조연산자, 인터페이스, final, 클래스와 인터페이스 간의 상속 문법


이클립스 설치

  • 1555290513997
  • https://www.eclipse.org/downloads/packages/
  • 우리는 Enterprise용으로 받는다~! // 밑에 있는 버전은 자바만 개발 가능하고, 위의 버전은 자바도 가능하고 HTML, JavaScript, Spring, Git 등이 사용 가능하기 때문에!
  • 첫 화면에서 다운 받으면 .exe 실행파일 되기 때문에, zip 파일 선호, 자칫 실행파일로 설치하면 개발 설정을 바꿀 수도 있기에…

  • 1555292175950

  • 작업공간 설정

  • 1555292331690

  • 1555292361723

  • Open Perspective 는 작업환경~, 기본적으로 제공하는 플러그인, 자바 프로젝트 하면 보통 Java와 Java EE를 사용

  • 자바 클래스 = 자바 빈, 아직 우리는 Java로 한다!

  • /*
         * 이클립스 단축 키 : 메뉴 window - Preferences - General - Keys
         * 
         * Ctrl + space : 자동완성
         * Ctrl + 1 : 제안기능
         * Ctrl + / : 한줄 주석 추가, 삭제
         * Ctrl + Alt + 아래 화살표 : 설택된 블럭을 복사하여 아래로 붙여넣기
         * Alt + 위 아래 화살표 : 선택된 블럭을 위 아래로 이동
         */
  • 나는 폰트는 cambria로~!

  • 패키지 이름 달리하면 병합 할때 좋다. 그래서 com.~~~ 이런식으로 이름을 구성한다!

  • 웬만하면 Refector - rename 은 하지 말자, 할거면 그냥 코드 복사해서 붙여 넣는 방법이 더 좋음, 왜? 이클립스가 좋은 부분 중 하나가 작성하고 저장하면 히스토리를 다 남김,

  • //package선언 : 현재 프로그램(클래스)의 위치 지정
    //형식 ) package 상위패키지명, 하위패키지명;

    //import 선언 : 현재 프로그램(클래스) 에서 사용할 외부 클래스의 위치 지정
    //형식 ) import 패키지명, 클래스명;

//지난 과제
package com.encore.$0415;

import java.io.IOException;

//package선언 : 현재 프로그램(클래스)의 위치 지정
//형식 ) package 상위패키지명, 하위패키지명;

//import 선언 : 현재 프로그램(클래스) 에서 사용할 외부 클래스의 위치 지정
//형식 ) import 패키지명, 클래스명;

public class MenuTest 
{
    public static void main( String[] args ) throws IOException 
    //System.in.read() 하면 에러가 발생할 수도 있는데 예외처리 안할래! 라는 의미.
    // 왜 IOException을 예외처리할까? 지난번엔 그냥 Exception 이었는데, 
    //추후에 배운다!
    {
        int num;
        int su = 0;// 증가 또는 감소한 값을 유지하기 위해 반복문 밖에 선언
        do
        {
        System.out.println( " < < 메 뉴 > > " );
        System.out.println( "1. 검색  2. 증가  3. 감소  4. 종료" );
        System.out.print( "번호를 입력하세요 ==>> " );
        num = System.in.read() - 48;
                     System.in.read(); // CR (13) 맨 앞으로 이동
                     System.in.read(); // LF (10) 줄 바꿈

        switch(num)
            {
            case 1 : System.out.println( "#검색 결과\n" + su); break;
            case 2 : su++; System.out.println( "#1증가"); break;
            case 3 : su--; System.out.println( "#1감소"); break;
            }
        System.out.println();
        }while( num != 4 );
        //자바에서 { } 는 영역가로 Scope , Body 라고 말함, 

        System.out.println( "-- END --" );
    }
}

<접근지정(제한)자 : AccessControl>

  • public
    • 서로 다른 패키지에서도 접근가능
  • protected

    • 서로 같은 패키지에서 접근가능, 만약 상속관계를 갖는다면 자식에서 부모를 참조할 수 있는 것.
  • default

    • 생략, 서로 같은 패키지에서 접근가능
  • private
    • 같은 클래스 내에서만 멤버끼리만 접근 가능
##p1패키지
class Parent
{
    public void m1(){}
    protected void m2(){}
    void m3(){}
    private void m4()P{} //m1, m2, m3 만 호출 가능 다른 패키지, 클래스에서 불가
}

class Child extends Parent
{
    // m1, m2, m3 접근 가능하나 m4에서는 접근 불가
}

================================
##p2패키지
class Child extends Parent
{
    //m1 접근 가능, m2 접근 가능(부자 관계이기 때문), m3 불가, m4 불가
}
================================
##p3패키지
class other
{
    //m1만 호출 가능, 같은 패키지도 아니며 부자 클래스 관계도 아니기 때문
}
  • 접근 지정자 위치

    1. 필드

      • [접근지정자 4개] 자료형 변수명;
    2. 메소드

      • [접근지정자 4개] 리턴자료형 메소드명(매개변수){}
    3. 클래스

      • [접근지정자 2개 (public , default 만 가능)] class 클래스명 {}
      • 클래스인데 만약 private가 된다면 그냥 쓰레기임…
  • 접근 지정자 뭐 해야 하는데 고민이라면 그냥 public 깔아두고 생각해보자,

직접 해보자!

//p1패키지

package p1;

//기준!! (서로 다른 접근 제한자를 갖는 메소드 정의)
public class Parent { 

        public void m1()
        {
            System.out.println("m1");
        }
        protected void m2()
        {
            System.out.println("m2");
        }
        void m3()
        {
            System.out.println("m3");
        }
        private void m4()
        {
            System.out.println("m4");
        }

}

package p1;

//자식에서 부모클래스의 메소드 호출
public class Child extends Parent{

    void callTest() {
        m1();
        m2();
        m3();
        //m4(); // 에러 The method m4() from the type Parent is not visible , 자식도 호출 불가
        //m5(); // 에러 The method m5() is undefined for the type Child
    }

}

package p1;

//자식에서 부모클래스의 메소드 호출
public class Other {

    void callTest() {
        //m1(); // 에러 The method m1() is undefined for the type Other
        //m2(); // 에러
        //m3(); // 에러
        //m4(); // 에러 The method m4() from the type Parent is not visible , 자식도 호출 불가
        //m5(); // 에러 The method m5() is undefined for the type Child

        Parent p = new Parent();
        p.m1();
        p.m2();
        p.m3();
        //p.m4(); // 에러 , The method m4() from the type Parent is not visible
    }

}
//p2 패키지
package p2;
//import 안하면 패키지 달라서 에러
import p1.Parent;

//자식에서 부모클래스의 메소드 호출
public class Child extends Parent{
    void callTest() {
        m1();
        m2(); //같은 패키지에서 접근 가능하다 하지만 상속관계인 부자 패키지 관계이면 패키지가 달라도 접근 가능!
        //m3(); // 에러, 디폴트는 패키지가 다르면 호출 불가
        //m4(); // 에러 The method m4() from the type Parent is not visible , 자식도 호출 불가
        //m5(); // 에러 The method m5() is undefined for the type Child
    }
}
//-------------------------
package p2;

import p1.Parent;

//자식에서 부모클래스의 메소드 호출
public class Other {
    void callTest() {
        //m1(); // 에러 The method m1() is undefined for the type Other
        //m2(); // 에러
        //m3(); // 에러
        //m4(); // 에러 The method m4() from the type Parent is not visible , 자식도 호출 불가
        //m5(); // 에러 The method m5() is undefined for the type Child

        Parent p = new Parent();
        p.m1(); // 왜 여기서는 에러가 발생하지 않은걸까요? public이기 때문~!
        //p.m2(); protected는 같은 패키지에서 접근 가능
        //p.m3(); 디폴트는 같은 패키지 내에서만 접근 가능
        //p.m4(); // 에러 , The method m4() from the type Parent is not visible
    }
}

자기 참조 연산자

  • 1반 홍길동, 2반 홍길동, 3반 홍길동 이 있는데 모두가 모인자리에서 특정 홍길동을 부를땐 2반 홍길동~! 이렇게 말해야 하지만, 2반 안에서 길동이를 찾을때는 굳이 그래야 하는 필요가 있을까? 보통은 생략하고 홍길동이라고 부른다 하지만 아래와 같은 경우에 사용한다!
  • 현재 클래스를 가르키는 레퍼런스 변수(참조변수)!
  • 보통은 생략

    1. 메소드 내에서 사용
    2. 객체 생성자내에서 다른 생성자를 호출시 사용
    3. 매개변수(지역변수)와 멤버변수(필드)를 구분하기 위해 멤버변수 앞에 this.을 붙여 사용.
//형식
this.필드명;
this.메솓명();
this(); //생성자 호출
//참고
super.필드명;
super.메소드명();
super(); //부모클래스 생성자 호출
  • 오른쪽 버튼 눌러서 - source - generate constructor using fields 로 쉽게 생성 가능

%생성자 만드는 단축키 컨 + 스 + 엔


인터페이스

  • 인터페이스는 메뉴판이다!, 유지보수하는데 이점이 있다.

    • 형식

    • “`java
      interface 인터페이스명
      {
      //필드
      [고정 public static final] int su;
      //여기서 static이란 new처럼 메모리 할당 할 수 있음
      //new는 동적메모리 할당, static은 정적 메모리 할당
      //여기서 final이란 마지막 변수라는 뜻, 절대 변하지 않는 수!

      //선언된 메소드
      [고정 public abstract] void print();
      //대괄호 생략 가능
      }

      
      - 저장 : 인터페이스명.java -> 컴파일 -> 인터페이스명.class
      
      - interface의 구성멤버는 필드, 선언된 메소드로만 구성
      
      - ```java
      void print()
      {
          //정의된 메소드, 구현된 메소드!
      }
      
      ///////////////////////선언된 메소드!
      void print(); // 기능 없이 이름만 선언된 메소드 ( 바디없는, 영역괄호 없는 메소드 )
      //단지 연결시켜준것, 메뉴판처럼 손님과 요리사를!

    < 손님의 입장 >

    • 서로 다른 제품에 연결할 수 있는 공통 연결 모듈을 의미.

    < 주방장의 입장 ( 객체를 생성하는 곳 ) >

    • 클래스에 다중 상속을 구현 할 수 있다.

    • ★ 인터페이스는 어떻게 사용? 클래스에 구현해서 사용!!

    • 구현 키워드 : implements

    • “`
      class 클래스명(//주방) implements(//구현의 약속) 인터페이스(//메뉴판)명
      {

    }
    “`

  • 실습

    package com.encore.$0415;
    
    public interface MenuPan 
    {
    // public static final 고정
    //final은 유지할 고정값을 명시해야 함
    
    
    //int coin; 에러 발생, 반드시 초기화 해야 함
    int coin = 500;
    /*public abstract 고정 생략*/void 짜장면();
    /*퍼블릭이 고정 생략*/abstract void 짬뽕(); //선언된 메소드 : abstract method
    public abstract void 볶음밥();
    }
    
    //============
    package com.encore.$0415;
    
    public class Hongkong implements MenuPan  //주방
    { 
    //implements : 구현의 약속
    @Override //어노테이션 JDK5버전 이후
    public void 짬뽕() 
    {
        System.out.println("매콤한 짬뽕");
    }
    @Override 
    public void 짜장면() 
    {
        System.out.println("달콤한 짜장면");  
    }
    @Override
    public void 볶음밥() 
    {
        System.out.println("갓볶은 볶음밥");  
    }
    public void 초밥() // 추가해도 상관 없다!
    {
        System.out.println("초밥 한입에 쏙~");
    }
    }
    
    //============
    package com.encore.$0415;
    
    public class InterfaceTest  //extedns String : 에러 발생
    {
    public static void main(String[] args) 
    {
        //손님
        MenuPan menu = new Hongkong(); 
        //인터페이스는 new 못씀
    
        menu.짬뽕();
        menu.짜장면();
        menu.볶음밥( );
    
        //static멤버는 클래스명으로 접근!!
        System.out.println("코인값 : " + MenuPan.coin);
    }
    }
    
    

Final

  1. final 자료형 변수명;

    • 마지막 변수 : 상수 (constant)
    • 상수의 식별을 위해 전체 대문자로 표기
    //예)
    final int max = 100;
    max++; >> 101 // 에러 발생!
  2. final 리턴형 메소드명 () {}

    • 마지막 메소드 : 오버라이딩(메소드 재정의) 할 수 없는 메소드.
  3. final class 클래스명{}

    • 마지막 클래스 : 클래스는 자식클래스를 통해 기능을 확장하는데, final 클래스는 무자식상팔자 클래스 : 자식 클래스를 갖지 않는 클래스
    • 완벽한 클래스(자식클래스 통한 기능확장을 원치 않는다.)
    • 보안적인 측면에서 사용하기도 함

<클래스와 인터페이스 간의 상속 문법>

class A{}

class B extends A //extends 뒤에는 상속 받고자 하는 한개의 클래스 명만 정의! 
{
    //extends 는 확장의 의미를 갖는다. 자식클래스를 확장 클래스라고도 함   
}
//============================================
interface A
{}
interface B
{}

class C implements A,B 
{}
//위와 대조하여 클래스는 무조건 한개의 클래스만 상속 가능하지만 interface는 , 를 사용하여 다중 인터페이스를 다중 상속 할 수 있다
// A와 B인터페이스 내의 선언된 메소드를 C클래스에서 전부 구현!, 구현의 약속!
//============================================
interface A{}
class B{}

//class C implements A extends B? 
// 얘는 에러가 발생함
//클래스와 인터페이스를 동시에 상속 할때에는 순서가 중요하다.
//클래스를 먼저 상속 받고 인터페이스는 나중에!
//implements가 먼저 나오면 컴파일러가 extends Object를 implements 키워드 앞에 추가해줌! 그래서 implements 가 두개가 되어버리는것... 에러!

class C extends B implements A // 로 해줘야 한다!
{

}

//============================================
interface A { void hello(); }
interface B { void hi(); }

interface C implements A,B {} 는 에러
interface C extends A,B {}
/*interface C extends A,B 
{
    void hello();
    void hi();

}
*/ //이렇게 기능을 가져오겠데...
//엥 이건 무슨 소리야?!
//A 안에는 hello(); 선언되어있음, hi();

//============================================
class A {void hello(){}}
interface B ㅁ A {} // 이런 경우는 절대 없다. 말이 안됨 extends는 내려준다라는 뜻인데 중괄호 있는 애를 어케 내려줌, 
// 주방을 물려받는 메뉴판은 없다.
  • mission

    package com.encore.$0415.misson;
    
    import java.io.IOException;
    
    /*
    * 기능정의
    * -단입력
    *    int inputDan ()
    * {
    *    int dan = read() 또는 readLine() 을 사용해서 받기 //그리고 단출력에 전달해야 함, return 타입 통해
    * }
    * 
    * -단출력
    *    void outputDan () 
    * {
    *    //전달받은 dan에 대한 출력
    * }
    * -계속여부
    *    char continueDan () 
    * {
    *    read() 또는 readLine()
    * }
    */
    
    public class Gugudan 
    {
    //public int dan;//=0
    //public char continuedan;//='\u0000'
    
    
    int inputDan() throws IOException
    {
        System.out.println("point");
        System.out.println("원하시는 단을 입력해주세요");
        int dan = System.in.read() - 48;
        System.in.read();
        System.in.read();
        return dan;
    
    }
    
    void outputDan(int dan)
    {
        System.out.println(dan + "단 구구단 출력");
        for (int i = 1; i <10; i++)
        {
            System.out.println(dan + "X" + i + " = " +  dan*i) ;
        }
    }
    
    char continueDan() throws IOException
    {
        System.out.println("계속하시겠습니까?");
        char continuedan = (char) (System.in.read());
        System.out.println(continuedan);
        System.in.read();
        System.in.read();
        return continuedan;
    
    }
    
    }
    
    
    //----------------
    
    package com.encore.$0415.misson;
    
    import java.io.IOException;
    
    /*
    * main() 포함
    * 반복적인 실행을 할 것(while 또는 do~while 사용 하면 됨)
    * 이번은 while로 해보자!
    * 반복문 내에서 Gugudan클래스 안에 3개의 메소드가 있는데 3개의 메소드들을 적당히 호출.
    */
    
    public class GugudanTest extends Gugudan
    {
    
    public static void main( String[] args) throws IOException
    {
        Gugudan g = new Gugudan(); 
    
    
        System.out.println("구구단");
    
        int dan = g.inputDan();
        g.outputDan(dan);
    
    //        
    //        g.inputDan();
    //        g.outputDan(dan);
    //        g.continueDan();
    //        
    
        while(g.continueDan() == 'y' )
        {
            dan = g.inputDan();
            g.outputDan(dan);
        }
            System.out.println("종료");
    }
    
    }
    
궁금상자
    - 패키지 이름 2개 이상 권장하는 이유?

    - jdbc

    - 어노테이션?

    - throw와 throws의 차이
        https://jhkim2017.wordpress.com/2017/04/24/java-throws%EC%99%80-throw%EC%9D%98-%EC%B0%A8%EC%9D%B4/
    - 자바 프로젝트 패키지 클래스 이해
        https://skyilcts.tistory.com/5
    - 패키지
        https://opentutorials.org/course/2517/14135
    - 인터패이스 패키지
        https://nittaku.tistory.com/46
        https://studymake.tistory.com/428
        https://opentutorials.org/module/2495/14142
    - 

+ Recent posts