• 텍스트필드에 단을 쓰고 구구단 버튼을 누르면 TextArea에 구구단 출력 (JGugudan)

    • JTextField, JButton, JTextArea메소드로 객체 생성, Frame상속받고 액션을 위해 ActionListener implements 시켜준다.

    • JTextField에 있는 문자를 받아서 정수형으로 반환한다.

    • 단을 가져와서 for문을 이용하여 출력한다.

    • 출력할때에는 JTextArea의 객체에 append()메소드를 이용한다.

    • 숫자가 아닌걸 parseInt하면 오류가 발생한다. 그때 오류 메시지를 써준다.

      • try-catch문으로 처리해주고 catch()메소드의 인자로 NumberFormatException n을 써준다. 

      • JTextField의 객체 tf1에 setText()메소드를 이용하여 오류 메시지를 쓴다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package guiTest;
 
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class JGugudan extends JFrame implements ActionListener{
    JTextField tf1;
    JTextArea ta1;
    int gugudan;
    int dan;
 
    public JGugudan() {
        setTitle("구구단");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        tf1=new JTextField(10);
        JButton b1=new JButton("구구단");
        ta1=new JTextArea(10,20);
        setLayout(new FlowLayout());
        add(tf1);
        add(b1);
        add(ta1);
        b1.addActionListener(this);
        tf1.addActionListener(this); //엔터를 누르면 버튼이 실행
        setSize(400,300);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new JGugudan();
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        ta1.setText(""); //그 전에 썼던 글자를 지우기 위해.
        //TextField에 있는 문자를 받아와서 정수형으로 반환
        //단을 가져와서 for문 이용
        try {
            //숫자가 아닌 걸 parseInt하면 오류발생. 그때 오류 메시지 써주기
            int dan = Integer.parseInt(tf1.getText()); 
            for(int i=1;i<10;i++) {
                ta1.append(dan+"*"+i+"="+dan*i+"\n");
            }
        } catch (NumberFormatException n) {
            tf1.setText("숫자를 입력하세요.");
        }
    }
}
  • 버튼을 패널로 묶고 패널 1 보이기, 안보이기 설정하기 (JPannelTest2)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package guiTest;
 
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
 
public class JPannelTest2 extends JFrame implements ActionListener{
    JPanel p1;
    JPanel p2;
    JTextArea ta;
    public JPannelTest2() {
        super("패널테스트");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //프레임이 닫힐때 메모리상에서도 종료
        p1=new JPanel(); //패널1
        p2=new JPanel(); //패널2
        ta=new JTextArea(10,20);
        JButton b1=new JButton("패널2 보이기");
        JButton b2=new JButton("패널2 안보이기");
        JButton b3=new JButton("패널1 보이기");
        JButton b4=new JButton("패널1 안보이기");
        setLayout(new FlowLayout());
        p1.add(b1); p1.add(b2); 
        p2.add(b3); p2.add(b4);
        add(p1); //패널을 프레임에 붙힌다.
        add(p2);
        add(ta);
        p1.setBackground(Color.yellow);
        p2.setBackground(Color.green);
        b1.addActionListener(this);
        b2.addActionListener(this);
        b3.addActionListener(this);
        b4.addActionListener(this);
        setSize(300,400);
        setVisible(true);
    }
    
    public static void main(String[] args) {
        new JPannelTest2();
    }
 
    @Override
    public void actionPerformed(ActionEvent e) {
        String str=e.getActionCommand();
        ta.append(str+"\n");
        if(str.equals("패널 2보이기")) {
            p2.setVisible(true);
        }else if(str.equals("패널 2안보이기")) {
            p2.setVisible(false);
        }else if(str.equals("패널 1보이기")) {
            p1.setVisible(true);
        }else {
            p1.setVisible(false);
        }
        
    }
}
 
  • Java GUI에는 awt, swing이 있다.  자바 패키지 내의 Java.awt/Javax.swing

  • Java.awt-프레임 위에 버튼을 만들고 이름적는 칸 만들기 (PannelTest)

    • 처리방식

      • 컴포넌트(버튼)를 만들고 이벤트 핸들러 (이벤트 처리 메소드)를 만들어서 연결시켜줘야한다.

      • 컴포넌트를 보여줄땐 컨테이너가 필요하다. 컨테이너로는 Frame, JFrame을 가장 많이 쓴다. 컨테이너에 컴포넌트를 부착시키는 형태인 것이다.

      • 따라서 Frame을 만들어서 Button을 올려야한다.

    • extend Frame

      • 컨테이너는 상속받아서 쓴다. 현재 작업 중인 클래스에 extend Frame을 하여 상속받는다. 

    • Frame에 제목 나타내기

      • super("제목") / setTitle("제목")을 통해 실행시 팝업되는 Frame의 제목을 붙일 수 있다.

      • Frame의 크기를 정하는 메소드는 setSize(가로, 세로)이다.

      • Frame을 나타내는 메소드는 setVisible(ture/false)이다.

    • Frame에 버튼 부착

      • add(버튼 클래스의 객체) 메소드를 이용하여 Frame에 버튼 객체들을 얹는다.

      • add()메소드를 여러개 쓰면 그 전에 쓴 버튼들은 나오지 않는다. 어떻게 보여줄 수 있을까?

    • 버튼 위치 정하기

      • 컴포넌트의 위치를 정할때에는 배치관리자를 사용한다. 배치관리자에는 BoardLayout이 있다.

      • setLayout이라는 메소드의 인자로 차례대로 배치하는 FlowLayout을 이용한다.

    • 버튼을 눌렀을때 이벤트가 발생

      • ActionListener라는 Interface에는 actionPerformed라는 메소드가 있다.

      • 작업중인 클래스에 ActionListener를 implements시켜준다.

      • 버튼이 눌러지는 이벤트를 발생시키려면 actionPerformed 메소드에 ActionEvent를 매개변수로 구현한다. (체크박스는 ItemEvent)

      • 버튼의 글자를 String으로 알려주기 위해 String형 객체를 선언하고 ActionEvent의 객체에 getActionCommand()메소드를 실행한다.

      • 버튼 들을 눌렀을때 각기 다른 출력문을 정할 수도 있고, setBackground(Color.컬러명)을 통해 Frame바탕의 색상을 변화시킬 수도 있다.

      • 출력문과 버튼을 연결하기 위해서는 버튼객체에 addActionListener메소드를 구현한다. 자신이 속한 클래스를 가리키는 this를 인자로 이용한다.

    • 텍스트 칸 만들기

      • 텍스트 칸은 TextField을 이용한다. 생성자 내부에 TextField 객체 tf1을 만들면 actionPerformed메소드에서 사용하지 못하므로 생성자 바깥에 써서 전역변수로 선언한다.

      • TextField객체로 마찬가지로 add()메소드를 이용하여 Frame에 얹는다.

    • TextField에 쓴 입력내용을 콘솔창에 출력하기

      •  actionPerformed메소드 내에서 tf1.getText()메소드를 이용한다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package guiTest;
 
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
public class PannelTest extends Frame implements ActionListener{
    TextField tf1;
    public PannelTest() {
        //super("GUI Test"); //frame의 제목
        setTitle("GUI Test"); //제목 붙이는 명령어
        Button b1=new Button("버튼1");
        Button b2=new Button("버튼2");
        Button b3=new Button("버튼3");
        tf1=new TextField(20); //이름 적는 칸 만들기. 생성자의 인자값으로 크기지정
        setLayout(new FlowLayout()); //FlowLayout:차례로 놓여지게함
        add(b1); //frame에 b1을 얹는다.
        add(b2); //버튼 1은 안나오고 버튼 2만 나옴
        add(b3);
        add(tf1);
        setSize(300,400); //frame의 크기를 300x400
        setVisible(true); //frame을 보여달라
        b1.addActionListener(this); //actionPerformed가 있는 위치를 가리킴. 같은 클래스 이므로 자기자신=this.
        b2.addActionListener(this);
        b3.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e) {
        String str=e.getActionCommand(); //버튼의 글자를 String형으로 알려줌
        if(str.equals("버튼1")) {
            System.out.println("버튼 1 이벤트 발생"); //이 이벤트를 누가 부를까? 버튼 1이 부른다고 할때 어떻게 연결할까?
            setBackground(Color.yellow);
            System.out.println(tf1.getText());
        }else if(str.equals("버튼2")) {
            System.out.println("버튼 2 이벤트 발생");
            setBackground(Color.BLUE);
        }else {
            System.out.println("버튼 3 이벤트 발생");
            setBackground(Color.pink);
        }
    }
    
    public static void main(String[] args) {
        new PannelTest();
        
    }
    
}
 

텍스트 칸에 ddd를 쓰고 버튼 1을 누르면 콘솔창에 그대로 출력된다.
버튼 2를 눌렀을때 blue 색상으로 변경된다.
버튼 3을 눌렀을때 pink색상으로 변경된다.

 


  • Javax.swing-프레임 위에 버튼을 만들고 이름적는 칸 만들기 (JpannelTest)

    • JFrame상속받기

      • extends JFrame으로 JFrame을 상속받는다.

      • JFrame은 X버튼을 누르면 닫힌다.

      • Swing은 자바 컴포넌트로 만들어진다.

    • 이벤트가 발생하도록 메소드 만들기

      • actionPerformed메소드를 만들고 작업중인 클래스에 ActionListener를 implements시켜준다.

      • actionPerformed메소드는 ActionEvent를 매개변수로 이용한다.

      • 버튼의 글자를 getActionCommand()로 String형으로 알려준다.

    • 버튼 생성

      • 버튼 생성은 JButton 클래스를 이용한다. add()메소드로 Frame에 붙이고 addActionListener메소드를 이용하여 actionPerformed메소드와 연결한다.

    • 텍스트 필드 생성

      • JTextField로 텍스트 칸을 만든다. 역시나 마찬가지로 actionPerformed메소드에서 이용해야 하므로 클래스 바깥에서 전역변수로 선언한다. add()메소드로 Frame에 붙인다.

    • 버튼 눌렀을때 Frame 백그라운드 색상 변경하기

      • Swing에서 Frame의 백그라운드 색상을 바꿀때에는 Container 객체를 생성해서 getContentPane()메소드를 이용한다. 

      • Container con=getContentPane(), con.setBackground(Color.컬러명)

    • 텍스트 필드에 쓴 글씨를 버튼 1을 눌렀을때 콘솔창에 나타내기

      • JTextfield 객체 jtf1.getText()로 내용을 가져온다.

      • setText()메소드를 이용하여 글자의 내용을 바꿀 수 있다. setText("")를 한다면 내용이 없어진다.

    • JTextArea(), TextArea()

      • 한 행을 쓰는 칸은 JTextField, 여러 행을 쓰는 칸은 JTextArea()메소드를 이용한다.

      • JTextArea(5,20)은 5행에 20글자를 쓸 수 있는 칸. 스크롤바가 없어서 칸을 넘어서 글을 쓰면 지워진다.

      • TextArea()는 awt패키지를 import해야 사용할 수 있는데 자동으로 스크롤바가 생긴다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package JPannel;
 
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
 
public class JpannelTest extends JFrame implements ActionListener{
    JTextField jtf1;
    public JpannelTest() {
        JButton b1=new JButton("버튼1");
        JButton b2=new JButton("버튼2");
        jtf1=new JTextField(20);
        JTextArea ta=new JTextArea(5,20); //5행 20글자
        TextArea tta=new TextArea(5,10); //스크롤바 생성
        setLayout(new FlowLayout());
        add(b1);
        add(b2);
        add(jtf1);
        add(ta);
        add(tta);
        b1.addActionListener(this);
        b2.addActionListener(this);
        setSize(300,400);
        setVisible(true);
    }
 
    public void actionPerformed(ActionEvent e) { //버튼이 눌러지는건 ActionEvent. 체크하는 건 ItemEvent
        String str=e.getActionCommand();
        Container con=getContentPane();
        if(str.equals("버튼1")) {
            System.out.println("버튼1 클릭");
            //색깔을 직접적으로 구현할 수는 없고 Container를 구해와서 getContentPane()메소드를 이용한다.
            con.setBackground(Color.yellow);
            System.out.println(jtf1.getText());
        }else {
            System.out.println("버튼2 클릭");
            con.setBackground(Color.blue);
            jtf1.setText("");
        }
    }
        
    public static void main(String[] args) {
        new JpannelTest(); //생성자 만들기
    }
}

 

 

 

  • 이클립스 src에 있는 파일을 읽어서 라인 앞에 번호를 붙여 출력하기 (FileInputOutputTest)

    • 파일을 한줄씩 읽기위해 Scanner 이용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package ioTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
//파일을 읽어서 라인 앞에 번호를 붙여 출력하기
import java.util.Scanner;
public class FileInputOutputTest {
    public static void main(String[] args) {
        Scanner sfis=null;
        PrintStream ps=null;
        try {
            sfis = new Scanner(new File("src\\ioTest\\input.txt"));
            ps = new PrintStream("src\\ioTest\\copy2.txt");
            int cnt=1;
            while(sfis.hasNext()) {
                String str = sfis.nextLine();
                ps.println(cnt+" "+str);        
                cnt++;
            }
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

+input.txt 내용

10:20
23:5
8:7
12:67
4:9
2:6
34:23
11:22
15:16

 

+출력문 copy2.txt 내용

1 10:20
2 23:5
3 8:7
4 12:67
5 4:9
6 2:6
7 34:23
8 11:22
9 15:16

 
  • DataInputStream과 DataOutputStream은 메모리에 저장된 0,1상태를 읽거나 쓴다. 그래서 자료형의 크기가 그대로 보존된다.  (DataStreamTest)

    • DataInputStream은 자료형별 메서드를 제공하여 자료형에 따라 읽거나 쓴다. (readByte, readChar, readInt 등..)

    • DataOutputStream은 read()에 대응되는 write()메소드를 사용한다. (writeByte, writeChar, writeInt 등..)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package ioTest;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DataStreamTest {
    public static void main(String[] args) {
        try {
            FileOutputStream fos=new FileOutputStream("data.txt");
            DataOutputStream dos=new DataOutputStream(fos);
            dos.writeByte(100);
            dos.writeChar('A');
            dos.writeInt(10);
            dos.writeFloat(3.14f);
            dos.writeUTF("Test");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            FileInputStream fis=new FileInputStream("data.txt");
            DataInputStream dis=new DataInputStream(fis);
            //write로 내보낸 자료형 순서대로 써야함
            System.out.println(dis.readByte());
            System.out.println(dis.readChar());
            System.out.println(dis.readInt());
            System.out.println(dis.readFloat());
            System.out.println(dis.readUTF());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

출처: Do it 자바 프로그래밍 입문 (548p-DataInputStream/DataOutputStream 테스트하기)

  • input.txt라는 텍스트 파일을 만들어서 같은 패키지 안에 저장한다. TokenFileTest라는 클래스를 만들고 input.txt 파일을 읽어서 콘솔창에 출력한다. (TokenFileTest)
  • 파일 읽는 클래스는 FileInputStream, 콘솔창 출력은 print메소드를 이용한다.

  • 읽어들임: read()는 int형만 읽어들이기 때문에 다양한 형식을 읽어들이기 위해 Scanner가 나왔다. (자바 5부터) 파일을 읽을때 Scanner를 써도 상관없다. 한 줄로 읽어들일때는 Scanner를 이용한다.

  • 내보낼때: write()는 FileOutputStream과 함께 쓰며 파일형태로 출력한다. print()는 콘솔창에 출력한다.

  • 객체 만들고 read, 객체 만들고 write, 예외처리 꼭 해주기.

  • 예외처리 할때 작은 범위의 예외처리를 먼저 써줘야함. (순서를 바꾸면 오류남)

+input.txt 내용

10:20

23:5

8:7

12:67

4:9

2:6

34:23

11:22

15:16

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package ioTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TokenFileTest {
    public static void main(String[] args) {
        try {
            //파일 경로를 정확하게 써주기
            FileInputStream fis=new FileInputStream("src\\ioTest\\input.txt");
            while(true) {
                int i = fis.read();
                if(i==-1break;
                System.out.print((char)i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

+만약에 파일로 내보내려면? (TokenFileTest)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package ioTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TokenFileTest {
    public static void main(String[] args) {
        try {
            //파일을 읽어들이는 객체 fis를 선언. 경로를 정확하게 써주기
            FileInputStream fis=new FileInputStream("src\\ioTest\\input.txt");
            //파일로 내보내는 객체 fos를 선언. 다음 경로에 txt파일이 만들어진다.
            FileOutputStream fos=new FileOutputStream("src\\iotest\\out.txt");
            while(true) {
                int i = fis.read();
                if(i==-1break;
                //System.out.print((char)i);
                //읽어들인 파일을 내보낼때 write.
                fos.write(i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

+파일의 내용을 한 줄씩 읽어들이고 한줄로 출력하고 싶다면? 또한 기존 파일 내용 중 10:20형태를 10 20으로 출력하려면? (TokenFileTest2)

    • 한 줄을 읽어들일 수 있는 Scanner 이용.  Scanner에서 파일 경로만 써주면 문자열로 인식하므로 new File을 붙여서 파일임을 표시.

    • while에는 이 객체가 있는 동안 돌린다는 뜻으로 hasNext()메소드 이용.

    • 한 줄씩 읽어들이는 nextLine()메소드 이용.

    • 문자열에서 쓰이는 split 함수를 이용하여 중간의 ' : '을 제거. 

    • split 함수는 String 배열로 지정해야함. 

    • 배열이므로 for문을 돌려서 출력하기 

+16진수로 출력한다면?

    • String 배열은 바로 16진수로 바꿀 수 없다.

    • parseInt로 먼저 변환한 뒤 정수형 변수에 선언하고

    • 그 정수형 변수를 16진수로 출력하기

+16진수로 변환한 결과물을 파일로 내보낸다면?

    • Scanner로 한 문장씩 입력받았기에 파일로 내보낼때는 PrintStream를 이용한다.

    • ps=new printStream이렇게 객체를 하나 만들어준다. 

    • write를에는 정수형이나 바이트의 배열만 할당할 수 있으므로 문자를 내보낼 수 있는 메소드 print()를 사용해야 한다.

    • 객체명을 앞에 붙여준다. (ps.print() 와 같은 형식)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package ioTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Scanner;
 
public class TokenFileTest2 {
    public static void main(String[] args) {
            /*10:20을 10 20으로 출력하기
             *한줄을 읽어들일 수 있는 Scanner를 이용하기
             *문자열 split 함수를 이용하여 ':'을 제거
             */
            //지역변수는 초기값이 없으면 안된다.
            Scanner sfis=null
            //문자를 내보낼때는 PrintStream을 많이 쓴다.
            PrintStream ps=null;
            try {
                //new File을 안쓰면 파일이 아니라 문자열로 인식한다.
                sfis = new Scanner(new File("src\\ioTest\\input.txt")); 
                ps = new PrintStream("src\\ioTest\\hex.txt");
                while(sfis.hasNext()) { //이 객체가 있는 동안 돌린다는 뜻. hasNext()
                    String str = sfis.nextLine();
                    String[]tmp=str.split(":");
                    for(int i=0;i<tmp.length;i++) {
                        System.out.print(tmp[i]+"\t"); 
                        /*16진수로 출력
                         *String 배열은 바로 16진수로 바꿀 수 없다.
                         *parseInt로 먼저 변환한 뒤 정수형 변수에 선언하고
                         *그 정수형 변수를 16진수로 출력하기 
                         */
                        int v=Integer.parseInt(tmp[i]);
                        System.out.print(Integer.toHexString(v).toUpperCase()+"\t");
                        //write에는 int나 byte의 배열만 할당할 수 있다. 문자를 내보낼 수 없다.
                        ps.print(Integer.toHexString(v).toUpperCase()+"\t");
                    }
                    //if(i==-1) break; hasNext()에서는 없으면 false로 넘어가니까 지워도 상관없음
                    //System.out.print(str+"\t");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                sfis.close();
                ps.close();
            }
        } 
}

 


  • StringTokenizer는 split메소드를 클래스화 시킨 것. 기본은 공백으로 쪼개기. (TokenTest)

Class StringTokenizer: 

StringTokenizer st = new StringTokenizer("this is a test");

    while (st.hasMoreTokens()) {

        System.out.println(st.nextToken());

}

=>출력문: 기본은 공백으로 쪼개는 것. 

    this

    is

    a

    test

    • 문자열을 미리 선언한 뒤 StringTokenizer의 객체를 불러서 쪼갤 기준을 지정할 수도 있고, StringTokenizer 생성자의 인수로 문자열을 쓸 수도 있다.  그때에는 공백이 기준이 된다.

    • 토큰 수는 countTokens(), 출력은 nextToken()메소드를 사용한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package utilTest;
import java.util.StringTokenizer;
public class TokenTest {
    public static void main(String[] args) {
        String str="aaa@bbb@ccc@ddd.eee";
        StringTokenizer stk=new StringTokenizer(str, "@."); //"@."=@로도, 점(.)으로도 쪼갠다.
        while(stk.hasMoreTokens()) { //hasMoreElements랑 같은 뜻
            System.out.println("토큰 수: "+stk.countTokens());
            System.out.println(stk.nextToken());
        }
        System.out.println("=======");
        
        StringTokenizer stk1=new StringTokenizer("1 0 14 15 3 3 19");
        while(stk1.hasMoreTokens()) {
            System.out.println("토큰 수: "+stk1.countTokens());
            System.out.println(stk1.nextToken());
        }
    }
}

 


  • TokenFileTest2에서 split대신에 StringTokenizer 클래스를 이용하기 (TokenFileTest3)

    • 8진수로 변환하고 octal.txt 파일로 출력하기 

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package ioTest;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
import java.util.StringTokenizer;
 
public class TokenFileTest3 {
    //input.txt파일을 읽어서
    //8진수로 변환하여 octal.txt파일로 출력하시오
    //단, StringTokenizer를 사용하기
    public static void main(String[] args) {
        Scanner sc=null;
        PrintStream pst=null;
        try {
            sc=new Scanner(new File("src\\ioTest\\input.txt"));
            pst=new PrintStream("src\\ioTest\\octal.txt");
            while(sc.hasNext()) {
                String str = sc.nextLine();
                StringTokenizer st=new StringTokenizer(str,":");
                while(st.hasMoreTokens()) { //Token이 있는 동안 
                    String tok=st.nextToken(); //Token하나를 가져와서 문자열 tok에 선언
                    int v=Integer.parseInt(tok);
                    System.out.print(Integer.toOctalString(v)+"\t");
                    pst.print(Integer.toOctalString(v)+"\t");
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            sc.close();
            pst.close();
        }
    }
}

 


  • 친구를 등록하고 파일로 출력하여 입력된 친구의 정보를 볼 수 있도록 만들기 (Friend, FriendMain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package ioTest;
import java.io.Serializable;
public class Friend implements Serializable{
    private String name;
    private String birth;
    private String addr;
    private String tel;
    //getter, setter 생성
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getBirth() {
        return birth;
    }
    public void setBirth(String birth) {
        this.birth = birth;
    }
    public String getAddr() {
        return addr;
    }
    public void setAddr(String addr) {
        this.addr = addr;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    
}

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package ioTest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Scanner;
public class FriendMain {
    //f의 값들을 Arraylist를 만들어서 저장시켜준다.
    //while문을 돌면 값들이 초기화가 되기 때문에 전역변수로 만들어주기 위해 맨 위에다가 쓴다.
    ArrayList<Friend>arr=new ArrayList<Friend>();
    File dir,file;
    @SuppressWarnings("unchecked")
    public FriendMain() throws IOException, ClassNotFoundException {
        dir=new File("src\\ioTest");
        file=new File(dir, "myFriend.txt");
        if(file.exists()) {//파일이 있으면
            ObjectInputStream ois=new ObjectInputStream(new FileInputStream(file));
            //Object은 반드시 캐스팅을 해줘야함
            arr=(ArrayList<Friend>)ois.readObject(); //ois파일을 읽어서 arr에 저장
        }else {
            file.createNewFile(); //파일 생성
        }
    }
    public void fileUse() throws FileNotFoundException, IOException {
        Scanner sc=new Scanner(System.in);
        while(true) {
            System.out.println("1.친구등록 2.친구보기 3.종료(저장)");
            int num=sc.nextInt();
            sc.nextLine(); //엔터를 치면 버려주기
            if(num==1) { //친구등록
                System.out.println("이름>>");
                String name=sc.nextLine();
                System.out.println("생일>>");
                String birth=sc.nextLine();
                System.out.println("주소>>");
                String addr=sc.nextLine();
                System.out.println("전화>>");
                String tel=sc.nextLine();
                //setter가 생성자 역할도 한다.
                //입력한 정보를 담을 때 f라는 객체를 이용한다.
                Friend f=new Friend();
                f.setAddr(addr);
                f.setBirth(birth);
                f.setName(name);
                f.setTel(tel);
                arr.add(f);
            }else if(num==2) { //친구보기
                for(Friend f:arr) {
                    System.out.println("이름: "+f.getName());
                    System.out.println("생일: "+f.getBirth());
                    System.out.println("주소: "+f.getAddr());
                    System.out.println("전화: "+f.getTel());
                }
            }else if(num==3) { //저장시켜놓고 종료하기
                //무엇을 저장하는가?
                //friend가 담긴 arraylist를 내보내야함. 객체를 어떻게 내보낼까?
                ObjectOutputStream oos=
                        new ObjectOutputStream(new FileOutputStream(file));
                //try-catch대신에 throws를 사용하기. 그 메소드를 호출하는 쪽에도 반드시 throws를 써주기
                //객체를 내보내는 writeObject메소드
                oos.writeObject(arr);
                System.out.println("종료");
                System.exit(0);
            }else { //입력오류
                System.out.println("입력오류");
            }
        }
    }
    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        FriendMain fm=new FriendMain();
        //생성자가 제일 먼저 실행되므로 ArrayList의 값들을 생성자에 저장시켜줘야한다.
        fm.fileUse();
    }
}

 


  • 파일 복사하기 (FileCopyTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package ioTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopyTest {
    public static void main(String[] args) {
        long millisecond=0;
        try{
        FileInputStream fis=new FileInputStream("src\\utilTest\\CapitalApp.java");
        FileOutputStream fos=new FileOutputStream("copy.txt");
            //파일 복사를 시작하기 전 시간
            millisecond=System.currentTimeMillis();
            int i;
            while((i=fis.read())!=-1) {
                fos.write(i);
            }
            //파일을 복사하는데 걸리는 시간 계산
            millisecond=System.currentTimeMillis()-millisecond;
        }catch(IOException e) {
            e.printStackTrace();
        }
        System.out.println("파일 복사하는 데: "+millisecond+" milliseconds 소요되었습니다.");
    }
}

출처: Do it 자바 프로그래밍 입문 (544p-파일복사하기)


  • 직렬화 테스트하기 (SerializationTest)

    • serial.out이라는 파일을 하나 만들어준다.

    • FriendMain에서는 ArrayList를 이용하여 한꺼번에 출력하였는데 여기서는 writeObject의 인수로 객체 하나씩 출력한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package ioTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Person implements Serializable {
    private static final long serialVersionUID=-1503252402544036183L;
    String name;
    //transient는 직렬화 시키지 말라는 뜻. transient를 쓰면 대표이사가 null이라 나옴
    //transient String job;
    String job;
    
    public Person() {}
    
    public Person(String name, String job) {
        this.name=name;
        this.job=job;
    }
    
    public String toString() {
        return name+","+job;
    }
}
public class SerializationTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Person personAhn=new Person("안재용""대표이사");
        Person personKim=new Person("김철수""상무이사");
        
        try{
            FileOutputStream fos=new FileOutputStream("serial.out");
            ObjectOutputStream oos=new ObjectOutputStream(fos);
            oos.writeObject(personAhn);
            oos.writeObject(personKim);
        }catch(IOException e) {
            e.printStackTrace();
        }
        try{
            FileInputStream fis=new FileInputStream("serial.out");
            ObjectInputStream ois=new ObjectInputStream(fis);
            Person p1=(Person)ois.readObject();
            Person p2=(Person)ois.readObject();
            
            System.out.println(p1);
            System.out.println(p2);
        }catch(IOException e) {
            e.printStackTrace();
        }
    }
}

출처: Do it 자바 프로그래밍 입문 (550p-직렬화 테스트하기)


  • File과 관련된 예제 (FileExam)

    • 폴더를 만들고 텍스트 파일도 하나 만들어서 저장한다.

    • listFiles()는 파일을 배열형태로 돌려준다. 배열이므로 for문을 써서 File f에 대입한다.

    • lastModified()는 마지막에 수정한 날짜를 long형태로 알려준다.

    • long형태가 아닌 알아보기 쉬운 형태로 바꾸기 위해 prinf()메소드를 이용한다. prinf는 출력하는 형태를 지정할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package ioTest;
 
import java.io.File;
 
public class FileExam {
 
    public static void main(String[] args) {
        File f1=new File("c:\\windows\\system.ini");
        //getPath()는 경로, getParent()는 부모 경로, getName()은 파일의 이름
        System.out.println(f1.getPath()+"="+f1.getParent()+"="+f1.getName());
        String res="";
        if(f1.isFile()) res="파일";
        else if(f1.isDirectory()) res="디렉토리";
        System.out.println(f1.getPath()+"은 "+res+" 입니다.");
        
        File f2=new File("folder");
        if(f2.isFile()) res="파일";
        else if(f2.isDirectory()) res="디렉토리";
        System.out.println(f2.getPath()+"은 "+res+" 입니다.");
        
        if(!f2.exists()) {
            System.out.println("파일없음");
        }
        System.out.println("----서브 리스트----");
        File[]subFiles=f2.listFiles(); //파일을 배열형태로 알려준다.
        for(int i=0;i<subFiles.length;i++) {
            File f=subFiles[i];
            long t=f.lastModified(); //마지막에 수정한 날짜를 long형태로 알려준다.
            //long형태가 아닌 알아보기 쉬운 날짜 형태로 바꾸기 위해 printf로 출력하는 형태를 지정
            System.out.println(f.getName());
            System.out.println("파일 크기: "+f.length());
            System.out.printf("수정한 시간: %ty년  %tb %td %ta %tT\n", t,t,t,t,t);
            //20년 6월 09 화 15:00:50 
        }
    }
}

 


  • 꼭 Object형태로 내보내지 않아도 된다. File형태로 내보내도 된다. (CapitalApp2)

    • utilTest패키지에 CapitalApp이 저장되어 있다는 가정하에 ioTest패키지에 CapitalApp2 클래스를 생성한다.

    • CapitalApp.showMenu()를 선언하면 오류가 발생한다. utilTest패키지에 있는 showMenu의 접근제어자를 default(생략)가 아닌 public으로 바꿔준다. CapitalApp클래스도 마찬가지로 public으로 바꿔준다.

    • 나라와 수도를 입력한 해쉬맵을 파일에 저장하고 종료하는 메소드인 save()를 생성한다.

    • FileWriter로 file형태로 내보낸다.  

    • 중복을 허용하지 않는 Set의 <String>형태로 나라만 가져오고, iterator로 나라를 방문한다. 나라와 수도를 key와 value변수를 선언하여 가져오고 write를 이용하여 나라와 수도를 출력한다

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package ioTest;
 
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
 
 
import utilTest.CapitalApp;
 
public class CapitalApp2 {
    private HashMap<StringString>map=new HashMap<StringString>();
    File dir,file;
    public CapitalApp2(){
        dir=new File("src\\ioTest");
        file=new File(dir,"myCapital.txt");
        map.clear();
        try {
        if(!file.exists()) { //파일 없음
            file.createNewFile(); //파일생성
            return;
         }
            //파일로부터 읽어오기 위해 만드는 스캐너
         Scanner scanner=new Scanner(file);
         while(scanner.hasNext()) {
             String country=scanner.next(); //나라
             String capital=scanner.next(); //수도
             map.put(country, capital);
         }
         scanner.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void input() {
        System.out.println("현재"+map.size()+" 개 나라와 수도 입력");
        while(true) {
            System.out.println("나라와 수도 입력(종료는 x)>>");
            String cont=CapitalApp.sc.next(); //나라
            if(cont.toUpperCase().equals("X")) break;
            if(map.containsKey(cont)==true) {
                System.out.println("이미 입력한 나라입니다.");
                continue;
            }
            String cap=CapitalApp.sc.next();
            map.put(cont,cap);
        }
    }
    
    private void quiz() {
        //Set: 중복을 허용하지 않는 자료구조
        Set<String> set=map.keySet();
        Object[]arr=set.toArray(); //toArray()를 이용하여 set을 배열형태로 변환
        while(true) {
            int n=(int)(Math.random()*map.size());
            //if(map.size()==0) return;
            //if(map.isEmpty()) return;
            //아무런 값도 입력하지 않은 상태에서 퀴즈풀기를 시도하면 오류가 뜬다.
            //try-catch문에 예외처리를 적어준다.
            String city="";
            try {
                city=(String)arr[n];
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println("map 이 비어 있습니다.");
                return;
            }
            String dosi=map.get(city);
            
            System.out.println(city+" 의 수도는? 종료는 x>>");
            String dap=CapitalApp.sc.next();
            if(dap.toLowerCase().equals("x")) {
                System.out.println("종료합니다.");
                break;
            }
            if(dap.equals(dosi)) {
                System.out.println("정답입니다.");
            }
            else {
                System.out.println("틀렸습니다.");
            }
        }
    }
    //해쉬맵을 파일에 저장하고 종료하는 메소드
    private void save() {
        FileWriter fw=null;
        try {
            fw=new FileWriter(file);
            Set<String> set=map.keySet(); //나라만 가져옴
            Iterator<String> it=set.iterator(); //나라를 방문하기 위해
            while(it.hasNext()) {
                String key=it.next(); //나라 가져옴
                String value=map.get(key); //수도를 가져옴
                fw.write(key+" "); //나라 출력
                fw.write(value+"\n"); //수도 출력
            }
            fw.close();
            System.out.println("종료");
            System.exit(0);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("파일저장 오류");
        }
    }
    
    public static void main(String[] args) {
        CapitalApp2 ca2=new CapitalApp2();
        while(true) {
            CapitalApp.showMenu();
            int choice=CapitalApp.sc.nextInt();
            switch(choice) {
            case 1 : ca2.input(); break;
            case 2 : ca2.quiz(); break;
            case 3 : ca2.save(); break;
            defaultSystem.out.println("입력오류");
            }
        }
    }
}
  • 해쉬맵에 간단한 영어사전을 만들기. 사용자로부터 영어단어를 입력받고 한글 단어 검색. exit 입력받으면 종료. (HashMapDic)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package utilTest;
import java.util.HashMap;
import java.util.Scanner;
public class HashMapDic {
    public static void main(String[] args) {
        
        HashMap<StringString>dic=new HashMap<StringString>();
        dic.put("baby""아기");
        dic.put("love""사랑");
        dic.put("apple""사과");
        //사용자로부터 영어 단어를 입력받고 한글 단어 검색.
        //"exit" 입력받으면 종료.
    
        while(true) {
            Scanner sc=new Scanner(System.in);
            System.out.println("영어단어 입력>> 종료 exit");
            String word=sc.nextLine();
            if(word.toLowerCase().equals("exit")) {
                System.out.println("종료합니다.");
                break;
            }
            String kor=dic.get(word); //get을 하면 value값이 리턴되니까 그 값이 있다고 미리 가정하는 것
            if(kor==null) {
                System.out.println(word+"는 없는 단어");
            }else {
                System.out.println(kor);
            }
        }System.out.println(dic);
    }
}
cs

 


  • 해쉬맵에는 자료형 뿐만 아니라 객체가 올 수 있다. 아이디를 입력했을때 학생 정보 출력하기 (HashMapStudent)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package utilTest;
import java.util.HashMap;
class Student{
    private String id;
    private String tel;
    private String name;
    
    public Student(String id, String tel, String name) {
        this.id = id;
        this.tel = tel;
        this.name = name;
    }
    public String getId() {
        return id;
    }
    public String getTel() {
        return tel;
    }
    public String getName() {
        return name;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", tel=" + tel + ", name=" + name + "]";
    }
}
public class HashMapStudent {
    
    public static void main(String[] args) {
        //id를 물어보면 학생이 있는지 알려줘야하니까 value값에는 클래스 Student가 들어감
        HashMap<String, Student>map=new HashMap<String, Student>();
        map.put("홍",new Student("1""010-1111-1111","홍길동"));
        map.put("이",new Student("2""010-2222-2222","이순신"));
        map.put("강",new Student("3""010-3333-3333","강감찬"));
        
        //키 값에 "홍"이 있을때의 value 값은?
        Student sid =map.get("홍");
        
        //System.out.println(sid.name)하면 오류남. name을 private이라 했으니.
        //따라서 name을 돌려주는 getter 메소드 가 필요함
        System.out.println(sid.getName());
        System.out.println(sid); //객체니까 주소값이 나올 수 밖에 없음.
        //주소 값이 안나오도록 toString()을 사용하여 오버라이딩 해야함.
        System.out.println(sid);
    
        System.out.println(sid.getTel());
    }
}
cs

 


  • Vector-동기화가 구현. iterator-메소드를 이용하여 객체 이동시킬 수 있다. hasNext()-그 다음에 이동할 공간이 있는지 물어보고 false라면 자동종료 (VectorTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package utilTest;
 
import java.util.Iterator;
import java.util.Vector;
 
public class VectorTest {
 
    public static void main(String[] args) {
        //Vector에는 동기화가 구현.
        Vector<Integer> v=new Vector<Integer>();
        v.add(5);
        v.add(new Integer(5)); //정확한 표현은 이렇게 클래스화를 하기..
        //Vector나 Arraylist는 중복이 됨. 순서에 중점.
        v.add(-1);
        v.add(2,100); //2는 위치값. 위치값을 안넣게 되면 맨끝에 붙음.
        for(Integer i:v) {
            System.out.print(i+"\t");
        }
        System.out.println();
        
        //iterator라는 메소드를 이용하여 객체를 이동시킬 수 있다. (for문 같은 것)
        //hasNext()는 그 다음에 이동할 공간이 있는지 물어봄. 나중에 false가 되면 자동으로 빠져나옴.
        Iterator<Integer> it=v.iterator();
        while(it.hasNext()) {
            System.out.print(it.next()+"\t");
        }
        System.out.println();
        
    }
}
cs

 


  • Set-중복을 허용하지 않는 자료구조. 나라를 보여주면 수도를 맞추는 어플. 해쉬맵의 key에 나라, value에 수도 값을 준다. 어플의 메뉴를 보여주고 사용자가 나라와 수도를 추가할 수 있으며, 나라를 알려주면 해당하는 수도를 맞추는 퀴즈를 풀 수 있다.  (CapitalApp)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package utilTest;
//나라를 보여주면 수도를 맞추는 어플
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;
public class CapitalApp {
    static Scanner sc=new Scanner(System.in);
    private HashMap<StringString>map=new HashMap<StringString>();
    public CapitalApp() {
        map.put("한국""서울");
        map.put("일본""동경");
        map.put("중국""베이찡");
        map.put("미국""워싱턴");
        map.put("영국""런던");
        map.put("프랑스""파리");
        map.put("독일""베를린");
    }
    
    static void showMenu() {
        System.out.println("***수도 맞추기 게임을 시작합니다.***");
        System.out.println("입력: 1, 퀴즈: 2, 종료: 3>>");
    }
    
    public void input() {
        System.out.println("현재 "+map.size()+" 개 나라와 수도 입력");
        while(true) {
            System.out.println("나라와 수도 입력(종료는 x)>>");
            String cont=sc.next(); //나라
            if(cont.toUpperCase().equals("X")) break;
            //맵에 입력한 나라가 있는지 확인
            if(map.containsKey(cont)==true) {
                System.out.println("이미 입력한 나라입니다.");
                continue//다시 반복문을 수행해라
            }
            String cap=sc.next(); //수도
            map.put(cont,cap);
        }
    }
    
    public void test() {
        //나라를 알려주면 해당하는 수도를 맞추는 퀴즈.
        //나라를 랜덤하게 알려줘야함. 맵의 특성은 랜덤하게 값을 저장한다는 것.
        //맵은 위치값으로 접근할 수 없다. 해쉬맵을 배열에 담아줘야 순서를 정할 수 있다.
        //컴퓨터가 랜덤하게 나라를 알려주면 그에 대한 수도를 입력. 그에 대한 정답, 오답 판단.
        //중복을 허용하지 않는 자료구조를 set이라 함
        Set<String> set = map.keySet();
        //배열로 변환
        Object[]arr=set.toArray(); //set을 배열 형태로 변환(순서를 알기위해)
        while(true) {
            int n=(int)(Math.random()*map.size());
            String city=(String)arr[n]; //나라 이름
            String dosi=map.get(city); //도시
            //문제출제
            System.out.println(city+" 의 수도는? 종료는 x>>");
            String dap=sc.next();
            if(dap.toLowerCase().equals("x")) {
                System.out.println("종료합니다.");
                break;
            }
            if(dap.equals(dosi)) {
                System.out.println("정답입니다.");
            }
            else {
                System.out.println("틀렸습니다.");
            }
        }
    }
        
    public static void main(String[] args) {
        CapitalApp ca=new CapitalApp();
        while(true) {
            //클래스 이름을 앞에 붙였단 것은 static으로 만들었다는 것.
            CapitalApp.showMenu();
            int choice=sc.nextInt();
            switch(choice) {
            case 1 : ca.input(); break;
            case 2 : ca.test(); break;
            case 3 : System.out.println("종료");
                     System.exit(0);
            default : System.out.println("입력오류");
            }
        }
    }
}
cs

 


  • 자바의 예외처리, try-catch문, finally. (ExceptionTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package exception;
//오류: 컴파일 오류, 실행 오류
//예외: 프로그램이 감지할 수 있는 오류
public class ExceptionTest01 {
    public static void main(String[] args) {
        int[]arr=new int[5];
        String str="";
        //오류가 날 법한 코드를 try안에 넣고
        //catch안에 어떤 오류인지 구분해서 변수와 함께 기재
        //보통 넓은 범위를 밑에 쓴다.
        try {
            System.out.println(str.length());
            for(int i=0;i<5;i++) {
                arr[i]=i;
                System.out.println(arr[i]);
            }
        }catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("예외발생");
        }catch (NullPointerException n) {
            System.out.println("null 값");
        }finally {
            //try가 수행되든 catch가 수행되든 반드시 수행되어야 하는 문장은 finally안에.
            System.out.println("반드시 수행되는 문장");
        }
        
    }
}
cs

 


  • Thread. 어떠한 영역을 누구나 접근할 수 있도록 비동기적으로 처리하는 것. 예를 들어 채팅에서 말하는 기능은 사용자가 동시에 할 수 있어야 한다. 사람이라는 클래스에서 speak란 함수가 있을때 20개의 사람 객체가 speak라는 메소드를 같이 쓰는 셈. 이게 Thread(가장 작은 실행 단위). start()라는 메소드 이름을 붙이면 run()으로 가서 자바 가상 머신(JVM)이 준비되어 있는 스레드를 실행시켜준다. (GuguThread, SaramTalk, SaramThread, SaramRunnable, GuguRunnable)

 

  • Thread를 이용하여 구구단 출력하기 (GuguThread)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package threadTest;
public class GuguThread extends Thread{
    //Thread는 jvm이 실행. start라고 메소드 이름을 붙이면
    //jvm이 알아서 run()을 실행.
    private int dan;
    
    public GuguThread(int dan) {
        this.dan=dan;
    }
    
    public void run() {
        int gugudan;
        System.out.println(dan+"단");
        for(int i=1;i<10;i++) {
            gugudan=dan*i;
            System.out.println(dan+"*"+i+": "+gugudan);
        }
    }
    
    public static void main(String[] args) {
        GuguThread g1=new GuguThread(5);
        g1.start();
        GuguThread g2=new GuguThread(7);
        g2.start();
        GuguThread g3=new GuguThread(3);
        g3.start();
    }
}

 


  • 일반적인 for문을 돌린 메소드 형태-차례대로 5번씩 값이 출력 (SaramTalk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package threadTest;
public class SaramTalk {
    private String name;
    
    public SaramTalk(String name) {
        this.name=name;
    }
    
    public void speak() {
        for(int i=0;i<5;i++) {
            System.out.println(name+" 이 말한다.");
        }
    }
    
    public static void main(String[] args) {
        SaramTalk s1=new SaramTalk("홍길동");
        SaramTalk s2=new SaramTalk("이순신");
        SaramTalk s3=new SaramTalk("강감찬");
        s1.speak();
        s2.speak();
        s3.speak();
    }
}

 

  • Thread형식으로 for문 출력-순서에 상관없이 5번씩 값이 출력 (SaramThread)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package threadTest;
public class SaramThread extends Thread {
    private String name;
    public SaramThread(String name) {
        this.name=name;
    }
    
    public void run() {
        for(int i=0;i<5;i++) {
            System.out.println(name+" 이 말한다.");
        }
    }
    
    public static void main(String[] args) {
        SaramThread s1=new SaramThread("홍길동");
        SaramThread s2=new SaramThread("이순신");
        SaramThread s3=new SaramThread("강감찬");
        s1.start();
        s2.start();
        s3.start();
    }
}

  • 자바에서 다중상속을 받기 위한 Runnable 인터페이스 상속. Thread와 함께 쓰이며 예외처리 가능. Thread 속도를 늦춰서 출력하기. (SaramRunnable)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package threadTest;
//자바에서 상속은 단일만 가능. Thread 이외에도 따로 상속받을 게 또 있다면?
//runnable이라는 인터페이스를 implements로 상속받으면 됨.
//인터페이스는 추상으로만 이루어져있기 때문에 반드시 추상메소드를 구현해야한다.
public class SaramRunnable implements Runnable{
    private String name;
    
    public SaramRunnable(String name) {
        this.name=name;
    }
    public static void main(String[] args) {
        SaramRunnable sr1=new SaramRunnable("홍길동");
        SaramRunnable sr2=new SaramRunnable("이순신");
        SaramRunnable sr3=new SaramRunnable("강감찬");
        Thread th1=new Thread(sr1);
        Thread th2=new Thread(sr2);
        Thread th3=new Thread(sr3);
        //Thread가 start를 부르기
        th1.start();
        th2.start();
        th3.start();
    }
    
    public void run() {
        for(int i=0;i<5;i++) {
            System.out.println(name+" 이 말한다.");
            try{
                Thread.sleep(1000); //1000ms->1초 동안 쉬어달라는 표시.
            }catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}
  • Runnable형식으로 구구단 출력하기 (GuguRunnable)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package threadTest;
public class GuguRunnable implements Runnable {
    private int dan;
    public GuguRunnable(int dan) {
        this.dan=dan;
    }
    
    public static void main(String[] args) {
        GuguRunnable g1=new GuguRunnable(5);
        Thread th1=new Thread(g1);
        th1.start();
        GuguRunnable g2=new GuguRunnable(7);
        Thread th2=new Thread(g2);
        th2.start();
        GuguRunnable g3=new GuguRunnable(3);
        Thread th3=new Thread(g3);
        th3.start();
    }
    @Override
    public void run() {
        int gugudan;
        System.out.println(dan+"단");
        for(int i=1;i<10;i++) {
            gugudan=dan*i;
            System.out.println(dan+"*"+i+": "+gugudan);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

 


  • 자바 API중 read. InputStream과 관련된 메소드. 값을 읽어들인다는 뜻. 입출력에 관계된 메소드들은 반드시 예외처리를 해줘야함. 입력받은 값을 텍스트 파일로 내보내고, 파일에서 값을 읽어서 출력하기. (InputTest, InputTest01, InputStreamTest, FileInputStreamTest)
  • read를 이용하여 정수형 변수 i에 값을 입력하기. 예외처리 해주기 (InputTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package ioTest;
import java.io.IOException;
public class InputTest {
    public static void main(String[] args) {
        while(true) {
            try {
                int i=System.in.read(); //System.in=input Stream.
                if(i==-1break;
                System.out.print((char)i);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

 

  • while문에 hasNext()의 조건(값을 입력하는 동안 유지)을 걸고 입력한 값을 그대로 출력하기. (InputTest01)
1
2
3
4
5
6
7
8
9
10
11
package ioTest;
import java.util.Scanner;
public class InputTest01 {
    public static void main(String[] args) {
        Scanner sc=new Scanner (System.in);
        while(sc.hasNext()) {//있는 동안
            String str=sc.next();
            System.out.println(str);
        }
    }
}

 

  • 파일로 내보내는 객체 fs를 만들기. 키보드로부터 받은 값을 텍스트파일에 입력하여 저장하기 (InputStreamTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package ioTest;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class InputStreamTest {
    public static void main(String[] args) {
        try {
            //파일로 내보내는 객체 fs를 만듦.
            FileOutputStream fs=new FileOutputStream("text.txt"); //refresh하면 text.txt파일이 생김
            while(true) {
                int i = System.in.read(); //키보드로부터 값을 받는다.
                if(i==-1break;
                fs.write(i); //콘솔로 입력받은 값을 내보내는 함수
            }
        }catch (FileNotFoundException e) {
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

  • 텍스트 파일을 읽어들여 그 파일의 내용을 출력하기 (FileInputTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputTest {
    public static void main(String[] args) {
        try {
            FileInputStream fis=new FileInputStream("text.txt");
            while(true) {
                int i = fis.read(); //fis는 FileInputStream의 객체
                if(i==-1break;
                System.out.print((char)i);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

  • Synchronized된 자바 파일을 읽어들이기, 합하여 파일로 출력하기 (FileTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package ioTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileTest {
    public static void main(String[] args) {
        try {
            //Synchronized된 자바 파일을 읽어들이기
            FileInputStream fis=new FileInputStream("src\\threadTest\\SynchronizedEx.java");
            FileOutputStream fos=new FileOutputStream("output.txt");
            int c;
            while((c=fis.read())!=-1) {
              System.out.print((char)c);
              fos.write(c);
            }
            fis.close();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 


 

  • String의 특징. 기본 데이터형이 아닌, 클래스형이다. (클래스형은 대문자로 시작) 클래스는 객체와 메소드를 가지고 있다(StringTest, StringTest02, StringTest03)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package utilTest;
public class StringTest {
     public static void main(String[] args) {
          //String은 클래스형. 기본데이터형이 아님. 클래스는 대문자로 시작.
          //클래스형은 new 로 객체를 만든다. 그런데 지금까지 String i=oo; 이런식으로 선언했었다.
          //어떻게 가능했던 걸까?
          //클래스는 주소값을 가지니까 str에는 100이란 주소값을 가지고 있고 출력할때 100이 가리키는 안녕이라는 값을 출력하는것.
          //==는 주소가 맞는지 물어본다. 그래서 str과 str1은 주소가 같기에 같다고 출력되고
          //equals는 내용이 맞는지 물어본다. 그래서 str과 tmp는 내용이 같기에 같다고 출력된다.
          String str="안녕";
          String str1="안녕";
          String tmp=new String("안녕");
          if(str==str1) {
              System.out.println("str==str1 주소 같다");
          }else {
              System.out.println("str==str1 주소 다르다");           
          }
          if(str==tmp) {
              System.out.println("str==tmp 주소 같다");
          }else {
              System.out.println("str==tmp 주소 다르다");              
          }
          if(str.equals(str1)) {
              System.out.println("str equals str1 내용 같다");
          }else {
              System.out.println("str equals str1 내용 다르다");           
          }
          if(str.equals(tmp)) {
              System.out.println("str equals tmp 내용 같다");
          }else {
              System.out.println("str equals tmp 내용 다르다");           
          }
          str=str+str1;
          //안녕안녕이 str에 담긴다. 원래있던 str의 안녕은 사라지고, 주소값도 달라진다.
          //String은 정적 클래스. 내용 수정이 불가하다.
          //동적클래스를 사용하는게 낫다. String Builder 혹은 String Buffer.
          if(str==str1) {
              System.out.println("주소 같다");
          }else {
              System.out.println("주소 다르다");
          }
     }
}

 

+ String클래스에 속한 함수들

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package utilTest;
public class StringTest02 {
     public static void main(String[] args) {
          String str="안녕하세요 Hello  지금은 자바 공부중!!!";
          System.out.println("str 길이: "+str.length()); //문자열의 길이
          System.out.println("H위치: "+str.indexOf('H'));
          System.out.println("H위치: "+str.indexOf("Hello")); //문자가 시작되는 위치
          System.out.println("4번째 문자의 위치: "+str.charAt(4));
          String tmp="열심히 합시다";
          System.out.println("str과 tmp 연결: "+str+tmp);
          System.out.println("str과 tmp 연결: "+str.concat(tmp));
          int value=7;
          System.out.println("str과 value 연결: "+str+value);
          //System.out.println("str과 value 연결: "+str.concat(value));
          //concat안에는 String형이 들어가야하는데 value는 int형.
          //String의 함수가 static으로 만들어졌기 때문에 클래스 이름으로 접근가능.
          //valueof를 통해 int형을 String형으로 변환.
          String s=String.valueOf(value);
          System.out.println("str과 value 연결: "+str.concat(s));
          System.out.println("tmp와 value 연결: "+tmp.concat(String.valueOf(value)));
          String msg="abcdefg";
          System.out.println(msg.toUpperCase());
          System.out.println(msg.toUpperCase().toLowerCase());
          String[]arr=str.split(" ");
          for(int i=0;i<arr.length;i++) {
              System.out.println(arr[i]);
          }
    System.out.println(arr.length);
     }
}

 

+String의 길이(문자열)를 출력, 그 문자열을 공백으로 구분하여 배열의 길이 출력, 16진수와 8진수로 변환하는 메소드

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package utilTest;
public class StringTest03 {
     public static void main(String[] args) {
          String tmp="1 0 15 23 6 21 17 10 11 12 13 14";
          //tmp의 길이를 출력. 문자열의 길이.
          System.out.println("tmp의 길이: "+tmp.length());
          
          //tmp를 공백으로 구분하여 배열의 길이 출력
          String []arr=tmp.split(" ");
          System.out.println("arr의 길이: "+arr.length);
          for(int i=0;i<arr.length;i++) {
              System.out.println(arr[i]+"\t");
          }System.out.println("====");
          
          //16진수
          //Integer라는 클래스에 toHexString을 쓰면 16진수로 바꿔준다.
          System.out.println(Integer.toHexString(15));
          
          /*
          arr배열안에 있는 숫자를 16진수로 변경
          문자를 숫자로 바꾸는 메소드 parseInt를 사용해야
          정수만 인수로 받는 toHexString을 통해 16진수로 변환시킬 수 있다.
          */
          String oct="";
          String hex="";
          for(int i=0;i<arr.length;i++) {
              int v=Integer.parseInt(arr[i]);
              oct+=Integer.toOctalString(v)+"\t";
               hex+=Integer.toHexString(v).toUpperCase()+"\t";
          }
          System.out.println("8진수: "+oct);
          System.out.println("16진수: "+hex);
          
     }
}
cs

  • 자바 API 중 Calendar 함수를 사용하여 현재 시각 출력하기 (CalendarTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package utilTest;
import java.util.Calendar;
public class CalendarTest {
     //static으로 된 함수는 static으로만 부를 수 있다.
     public static void printCalendar(String msg, Calendar cal) {//now는 Calendar형
          //년,월,일 출력
          int year=cal.get(Calendar.YEAR); //년
          int month=cal.get(Calendar.MONTH)+1//0부터 되어있기 때문에 현재의 월을 출력하려면 +1.
          int day=cal.get(Calendar.DAY_OF_MONTH); //일
          System.out.println(year+"/"+month+"/"+day);
          //요일
            System.out.println(cal.get(Calendar.DAY_OF_WEEK)); //일요일부터 센다.
          int d=cal.get(Calendar.DAY_OF_WEEK);
          String yul="";
          switch(d) {
          case Calendar.SUNDAY : yul="일"break;
          case Calendar.MONDAY : yul="월"break;
          case Calendar.TUESDAY : yul="화"break;
          case Calendar.WEDNESDAY : yul="수"break;
          case Calendar.THURSDAY : yul="목"break;
          case Calendar.FRIDAY : yul="금"break;
          case Calendar.SATURDAY : yul="토"break;
          }
          System.out.println("요일: "+yul);
          System.out.println(Calendar.SUNDAY); //1
          int ampm=cal.get(Calendar.AM_PM);
          String ampmStr="";
          /*
          if(ampm==Calendar.AM) {
               ampmStr="오전";
          }else {
               ampmStr="오후";
          }
          */
          ampmStr=(ampm==Calendar.AM)? "오전":"오후";
          int h=cal.get(Calendar.HOUR);
          int m=cal.get(Calendar.MINUTE);
          int s=cal.get(Calendar.SECOND);
          System.out.println("현재시각: "+ampmStr+" "+h+":"+m+":"+s);
     }
     public static void main(String[] args) {
          Calendar now=Calendar.getInstance();
          CalendarTest.printCalendar("현재", now);
     }    
}

 


  • StringBuilder사용하여 문자열 출력하기 (StringBuilderTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package utilTest;
public class StringBuilderTest {
    public static void main(String[] args) {
        String str="string";
        //StringBuilder는 문자를 동적으로 받기때문에 출력, 삭제 등이 간편
        StringBuilder sb=new StringBuilder(str);
        System.out.println(sb);
        sb.append("자바"); //맨 뒤에 문자 삽입
        System.out.println(sb);
        sb.insert(2"oracle"); //위치를 지정하여 문자 삽입
        System.out.println(sb); //storaclering자바
        System.out.println(sb.toString()); //toString은 문자로 바꾼다.
        sb.delete(25);
        System.out.println(sb); //인덱스 2앞에 커서가 있다고 생각. o,r,a가 없어짐. stclering자바
        sb.reverse();
        System.out.println(sb); //문자열 거꾸로 출력
        System.out.println(sb.charAt(3)); //3번째 있는 문자 출력
        System.out.println(sb.substring(3)); //문자 추출: 인덱스 3번째부터 끝까지 출력
        System.out.println(sb.substring(3,5)); //3에서 부터 5전까지 출력.
    }
}
cs

 


  • 입력한 문장의 길이만큼 반복하여 첫번째 글자를 맨뒤에 붙여서 출력하기. (StringTest04)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package utilTest;
import java.util.Scanner;
public class StringTest04 {
        
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("문장입력>>");
        String line=sc.nextLine();
        //문장의 길이만큼 반복
        for(int i=0;i<line.length();i++){
            //첫글자 구하기
            //String first=line.substring(0,1);
            char first=line.charAt(0);
            //두번째부터 끝까지 구하기
            String second=line.substring(1);
            //2+1하기
            line=second+first;
            System.out.println(line);
        }
        
    }
}

 


  • key와 value로 구성된 HashMap (HashMapTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package utilTest;
 
import java.util.HashMap;
 
public class HashMapTest {
 
    public static void main(String[] args) {
        //Key와 Value로 구성된 Map이란 자료구조.
        HashMap<StringString> hm=new HashMap<StringString>();
        //Map에 저장하는 명령어는 put.
        //순서는 중요하지 않고 값만 돌려줌.
        hm.put("one""첫번째");
        hm.put("two""두번째");
        hm.put("three""세번째");
        hm.put("four""네번째");
        System.out.println(hm);
        System.out.println(hm.size()); //크기는 length가 아닌 size();
        hm.put("one""첫번째 one"); //키가 중복되면 허용하지 않고 덮어쓰기가 된다.
        System.out.println(hm);
        System.out.println(hm.size());
        System.out.println(hm.get("two")); //두번째. get의 인수로 키를 적으면 value값을 알려줌.
        hm.put("1","새로넣음");
        System.out.println(hm);
        
        //key의 값을 출력하려면 keySet()함수 이용.
        for(String s:hm.keySet()) {
            System.out.println(s);
        }
        //value값을 출력하려면 get()함수 이용
        for(String s:hm.keySet()) {
            System.out.println(hm.get(s));
        }
        System.out.println(hm.containsKey("1")); //true. key값에 1이 있는지 물어봄
        System.out.println(hm.containsValue("두번째")); //true. value값에 두번째가 있는지 물어봄
        
        //value값을 출력하는 또다른 함수 values()
        for(String s:hm.values()) {
            System.out.println(s); 
        }
        
    }
}
 

  • HashMap에 key와 value를 넣고 id과 비번이 일치하는지 출력하기 (HashMapTest02)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package utilTest;
 
import java.util.HashMap;
import java.util.Scanner;
 
public class HashMapTest02 {
 
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        HashMap<StringString> map=new HashMap<StringString>();
        map.put("java""1111");
        map.put("oracle""1234");
        map.put("jsp""abcd");
 
        System.out.println("ID를 입력하세요");
        String id=sc.nextLine();
        
        System.out.println("패스워드를 입력하세요");
        String pw=sc.nextLine();
        
        if(map.containsKey(id)==false) { //id가 없음
            System.out.println("ID 존재 안함");
        }
        //get(key)이 가리키는 value값과 pw가 일치하는지 물어봄.
        else if(map.get(id).equals(pw)==false) {//비번오류
            System.out.println("비번 일치 하지 않음");
        }
        else {
            System.out.println("ID/PWD 일치");
        }
    }
}

  • 1부터 20사이의 난수 10개를 map에 넣으시오. 키 값은 1~10, value값은 1~20사이 난수. 중복된 난수를 허용하지 않는다. map의 values 값들을 작은 값부터 정렬-Collection.sort()(Test01)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package utilTest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test01 {
    public static void main(String[] args) {
        //1부터 20사이의 난수 10개를 map에 넣으시오
        //키 값은 1~10, value값은 1~20사이 난수
        //단 중복된 난수는 허용하지 않는다.
        Map<Integer, Integer> map=new HashMap<Integer, Integer>();
        for(int i=1;i<11;i++) {
            while(true) {
                int value=(int)(Math.random()*20)+1//1에서 20사이
                if(!map.containsValue(value)) {
                    //map.containsValue(value)==false와 같은말
                    //value가 없으면 value값에 넣으란 소리.
                    //중복된 게 있으면 키값도 삭제해버리니까 while문을 쓰는게 좋음
                map.put(i,value);
                break;
                }
            }
        }
        for(Integer i:map.values()) {
            System.out.print(i+"\t");
        }
        System.out.println();
        System.out.println(map);
        
        System.out.println();
        //map에 들어있는 value값들을 Integer형 ArrayList에 담는다.
        List<Integer>list=new ArrayList<Integer>(map.values());
        //작은값부터 정렬한다.
        Collections.sort(list);
        for(int i:list) {
            System.out.print(i+"\t");
        }
System.out.println();
    }
}

 


  • 문장의 한글자마다 2씩 더하여 암호화 하고 다시 2씩 빼서 복호화하여 출력하기 (EncTest)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package utilTest;
public class EncTest {
    public String encrypt(String msg) {
        String dap="";
        for(int i=0;i<msg.length();i++) {
            //공백이면. 한글자이기 때문에 char.''홑따옴표
            if(msg.charAt(i)==' ') {
                dap+=msg.charAt(i);
            }else {
                dap+=(char)(msg.charAt(i)+2); //누적시키기위해 +=.  
            }
        }
        return dap;
    }
    
    public String decrypt(String str1) {
        String bok="";
        for(int i=0;i<str1.length();i++) {
            //공백이면. 한글자이기 때문에 char.''홑따옴표
            if(str1.charAt(i)==' ') {
                bok+=str1.charAt(i);
            }else {
                bok+=(char)(str1.charAt(i)-2); //누적시키기위해 +=.  
            }
        }
        return bok;
    }
    
    public static void main(String[] args) {
        EncTest enc=new EncTest();
        String msg="Hi..Glad to meet you!!";
        System.out.println("암호화 전: "+msg);
        //한 문자에 2씩 더하기
        String str1=enc.encrypt(msg);
        System.out.println("암호화 후: "+str1);
        System.out.println("복호화 후: "+enc.decrypt(str1));
    }
}

 

+StringBuilder를 활용하여 똑같이 재현하기 (EncBuilderTest)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package utilTest;
 
public class EncBuilderTest {
    private StringBuilder encrypt(String msg) {
        StringBuilder sb=new StringBuilder();
 
        for(int i=0;i<msg.length();i++) {
            if(msg.charAt(i)==' ') { 
                sb.append(msg.charAt(i));
            }else {
                sb.append((char)(msg.charAt(i)+2));
            }
        }
        return sb;
    }
    
    private StringBuilder decrypt(String msg) {
        StringBuilder sb=new StringBuilder();
 
        for(int i=0;i<msg.length();i++) {
            if(msg.charAt(i)==' ') { 
                sb.append(msg.charAt(i));
            }else {
                sb.append((char)(msg.charAt(i)-2));
            }
        }
        return sb;
    }
 
    
    public static void main(String[] args) {
        EncBuilderTest eb=new EncBuilderTest();
        String msg="Hi..Glad to meet you!!";
        System.out.println("암호화 전: "+msg); 
        //한 문자에 2씩 더하기
        String str1=eb.encrypt(msg).toString(); //문자로 바꾸는 toString();
        System.out.println("암호화 후: "+str1);
        System.out.println("복호화 후: "+eb.decrypt(str1));
    }
}

  • 해쉬맵 map을 생성, 단어를 입력받아 단어와 입력 횟수 저장, 대소문자 구분없이 x치면 종료. map을 출력하기. map에 키값에 해당하는 단어가 있으면 values 수에 1을 더하고 단어가 없으면 1을 추가한다. (HashMapTest)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package utilTest;
import java.util.HashMap;
import java.util.Scanner;
public class HashMapTest03 {
    public static void main(String[] args) {
        /* 1.해쉬맵 map을 생성
         * 2.단어를 입력받아 단어와 입력 횟수 저장
         * 3.대소문자 구분없이 x치면 종료.
         * 4.map출력
         */
        HashMap<String, Integer>map=new HashMap<String, Integer>();
        Scanner sc=new Scanner(System.in);
        while(true) {
            System.out.println("단어를 입력하세요. 종료 x>>");
            String word=sc.nextLine();
                if(word.toLowerCase().equals("x")) break;
                if(map.containsKey(word)) { //map에 단어가 있으면 그 수에 1더하기
                    map.put(word,map.get(word)+1);
                }else { //map에 단어가 없으면 1추가
                    map.put(word,1);
                }
        }System.out.println(map);
    }
}

 

  • 자바의 다형성-상위 클래스를 통해 하위 클래스의 값을 다양한 형태로 돌려줌. 각 도형의 넓이의 합을 구할때. (Shape, ShapeMain, ShapeManager, Circle, Square)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package day07;
import java.util.Scanner;
public class ShapeMain {
     static Scanner sc=new Scanner(System.in);
     
     public static void showMenu() {
          System.out.println("선택하세요...");
          System.out.println("1.원 2.사각형 3.보기 4.종료");
          System.out.print("선택:");
     }
     
     public static void main(String[] args) {
              ShapeManager sm=new ShapeManager();
              
              while(true) {
              ShapeMain.showMenu();
              //클래스 이름에 static 불였으니까 ShapeMain으로 부를 수 있음.
              int num=sc.nextInt();
              switch(num) {
              case 1 : //원입력
              case 2 : sm.inputData(num); break//사각형입력
              case 3 : sm.viewData(); break//전체보기
              case 4 : System.out.println("종료");
                         System.exit(0);
              default : System.out.println("입력오류");
              }
          }
     }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package day07;
public class ShapeManager {
     //입력받은 좌표, 반지름, 너비, 높이 등을 저장하기 위해 배열 선언
     //부모형으로 선언을 해야 Circle, Square 모두 적용가능
     Shape[]arr=new Shape[50];
     int cnt;
     
     public void inputData(int num) { //원->x,y,r 사각형->x,y,w,h
          System.out.println("도형입력....");
          System.out.print("x 좌표>>");
          int x=ShapeMain.sc.nextInt();
          System.out.print("y 좌표>>");
          int y=ShapeMain.sc.nextInt();
          
          if(num==1) { //원
              System.out.print("반지름>>");
              int r=ShapeMain.sc.nextInt();
              arr[cnt++]=new Circle(x,y,r);
          }
          else if(num==2) { //사각형
              System.out.print("너비>>");
              int w=ShapeMain.sc.nextInt();
              System.out.print("높이>>");
              int h=ShapeMain.sc.nextInt();
              arr[cnt++]=new Square(x,y,w,h);
          }
     }
     
     public void viewData() {
          double sum=0;
          for(Shape s: arr) {
              if(s==nullbreak;
              sum+=s.getArea();
              s.print();
          }
          System.out.println("전체 넓이: "+sum);
     }
     
}

 

 

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

 

 

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

 

 

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

 


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

 

 

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

 

 

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

 

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

 

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

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
package inheritance;
public class Buyer {
     private int money;
     private int point;
     Product[] arr=new Product[10];
     int cnt;
     
     public Buyer(int money) { //생성자는 클래스 이름과 똑같이 만듦.
          this.money=money;
     }
     //구매하기
     public void buy(Product p) {
          arr[cnt++]=p;
          money-=p.price; //바이어가 가진 돈은 물건의 가격만큼 깎인다.
          point+=p.bonusPoint;
     }
     //구매내역
     public void showInfo() {
          for(int i=0;i<cnt;i++) {
              System.out.println("구매내역: "+arr[i]);
              //그냥 배열만 출력하면 주소값이 나옴.
          }
          System.out.println("잔액: "+money);
          System.out.println("포인트: "+point);
          
     }    
}

  • 객체 따로 선언하지 않고 클래스 형태를 매개변수로 적기, instanceof (AnimalTest1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package inheritance;
 
class Animal{
    public void move() {
        System.out.println("동물이 움직입니다.");
    }
}
 
class Human extends Animal {
    public void move() {
        System.out.println("사람이 두 발로 걷습니다.");
    }
}
 
class Tiger extends Animal {
    public void move() {
        System.out.println("호랑이가 네 발로 뜁니다.");
    }
}
 
class Eagle extends Animal {
    public void move() {
        System.out.println("독수리가 하늘을 납니다.");
    }
}
 
public class AnimalTest1 {
    public static void main(String[] args) {
        AnimalTest1 aTest=new AnimalTest1();
        aTest.moveAnimal(new Human()); 
        aTest.moveAnimal(new Tiger()); //한번만 쓰고 더이상 안만들 것은 객체를 따로 선언하지 않고 new Tiger()이런 식으로 매개변수로 적어줌
        aTest.moveAnimal(new Eagle());
        
        Human h=new Human();
        if(h instanceof Animal) { //instanceof는 이 객체가 어느 소속인지 물어보는 키워드. Human보다 Animal이 상위 개념이므로 맞다라고 출력. 
            System.out.println("맞다");
        }else {
            System.out.println("틀리다");
        }
        
        Animal a=new Animal();
        if(a instanceof Human) { //a는 Animal. Human보다 큰 개념이므로 틀리다11가 출력.
            System.out.println("맞다11");
        }else {
            System.out.println("틀리다11");
        }
        
    }
    
    public void moveAnimal(Animal animal) { //Animal에서 상속받은 클래스가 매개변수로 넘어오면 모두 Animal형으로 변환됨. animal에 휴먼, 타이거, 이글 등..올수 있음.
        animal.move();
    }
}
 

 


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

 

 

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

 

 

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

 

 

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

 


  • 추상클래스 (Player, PlayerLevel, BeginnerLevel, AdvancedLevel, SuperLevel, MainBoard)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
package inheritance;
public class Player {
     private PlayerLevel level; //PlayerLevel이 가지는 level변수 선언
     
     public Player() {
          level=new BeginnerLevel();
          level.showLevelMessage();
     }
     
     public PlayerLevel getLevel() {
          return level;
     }
     
     public void upgradeLevel(PlayerLevel level) { //매개변수 자료형은 모든 레벨로 변환 가능한 PlayerLevel
          this.level=level; //현재 자신의 level을 매개변수로 받은 level로 변경하고 레벨 메시지 출력
          level.showLevelMessage();
     }
     
     public void play(int count) { //PlayerLevel의 템플릿 메서드 go()호출
          level.go(count);
     }
     
}

 

 

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

 

 

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

 

 

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

 

 

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

 

 

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

 


  • 전부다 추상인걸로 이뤄진 것을 interface라 하고 extends가 아닌 implements를 사용. 추상과 마찬가지로 new라는 키워드로 생성불가능하지만 추상과 달리 여러개를 상속받을 수 있다. 자바의 불가능한 다중 상속을 가능하게 만들기 위해 extends와 implements를 함께 쓴다. (InterExam)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package inheritance;
interface InterTest{
     public void test();
}
//전부다 추상이라면 추상클래스라 안붙이고 interface를 붙인다.
interface InterShape{
     public void draw();
     public void move();
     public void print();
}
//interface는 extends가 아닌 implements를 사용.
class InterCircle implements InterShape, InterTest{
     //하위 클래스가 상위 추상 클래스의 메소드를 부를때는 구현(중괄호 {})해야함.꼭.
     //InterTest도 상속받았기 때문에 test(){}도 구현.
     public void draw() {}
     public void move() {}
     public void print() {}
     public void test() {}
}
class Inter {
     public void interTest() {
     }
}
//자바는 다중 상속이 안되게끔 되어있는데 다중 상속을 받아야할때는 이렇게 표현.
//상속을 받고 interface를 써줌.
class InterRectangle extends Inter implements InterShape,
InterTest{
     public void draw() {}
     public void move() {}
     public void print() {}
     public void test() {}
}
public class InterExam {
}

 


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

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package interfaceTest;
public interface Shape {
     double area(); //넓이
     double circum(); //둘레 
}
class Rectangle implements Shape{
     private int w, h;
     public Rectangle(int w, int h) {
          this.w=w;
          this.h=h;
     }
     public double area() {
          return w*h;
     }
     public double circum() {
          return (w+h)*2;
     }
}
class Circle implements Shape{
     private int r;
     public Circle (int r) {
          this.r=r;
     }
     public double area() {
          //Math는 수학적 계산이 완료된 클래스.
          //멤버변수로 PI가 그 중 하나.
          return r*r*Math.PI;
     }
     public double circum() {
          return 2*r*Math.PI;
     }
}

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

 

 

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

 

 

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

 

 

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

 


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

 

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

 


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

 

<ShapeManager>

Shape[]arr=new Shape[50]; 

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

 

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

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

 

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

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

 

for(Shape s: slist){

    sum+=s.getArea();

    s.print();
}


<Buyer>

Product[] arr=new Product[10];

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

 

arr[cnt++]=p;

->list.add(p);

 

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

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

 

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

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

  • 이차원배열의 인덱스 값을 일차원배열로 지정, 출력 순서를 행 단위로 바꾸기 (ShiftArray)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package day06_objectArray;
public class ShiftArray {
     
     public static void shiftArray(int [][]arr) {
          //일차원 배열을 만들고 그 배열에 arr의 마지막 행 값을 넣는다.
          int []tmp=arr[arr.length-1];
          //arr의 인덱스가 2에 1의 값을 넣는다.
          //arr의 인덱스가 1에 0의 값을 넣는다.       
          for(int i=arr.length-2;i>=0;i--) {
                   arr[i+1]=arr[i];
              }
          //arr의 인덱스가 0의 위치에 처음 만든 일차원 배열을 넣는다.
          arr[0]=tmp;
     }
     
     public static void showArray(int [][]arr) {
          for(int i=0;i<arr.length;i++) {
              for(int j=0;j<arr[i].length;j++) {
                   System.out.print(arr[i][j]+"\t");
              }System.out.println();
          }
     }
     
     
     public static void main(String[] args) {
          int [][]arr= {{1,2,3},{4,5,6},{7,8,9},{10,11,12}};
          
          System.out.println("1차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          System.out.println("2차 shift...");
          ShiftArray.shiftArray(arr); //이동메소드
          ShiftArray.showArray(arr);  //출력메소드
          /*
           * 1차 shift...
           * 7 8 9
           * 1 2 3
           * 4 5 6
           * 2차 shift...
           * 4 5 6
           * 7 8 9
          */
     }
}

 


  • ArrayList활용. 학생의 학번, 이름, 과목 성적 입력하고 출력하기 (StudentTest, Student, Subject)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package day06_objectArray.arraylist;
//import java.util.ArrayList;
public class Student {
     int studentID;
     String studentName;
     Subject []subjectList;
     int index;
     //ArrayList<Subject>subjectList;
     
     public Student(int studentID, String studentName) {
          this.studentID=studentID;
          this.studentName=studentName;
          subjectList=new Subject[10];
          //subjectList=new ArrayList<Subject>();
     }
     //배열을 대신해서 사용할 수 있는게 ArrayList.
     //학생이 여러 과목을 듣는데 그걸 따로 과목에 대한 클래스로 따로 분류
     //그걸 배열에 담음.
     //배열은 처음에 공간을 정해줘야함. 대신에 ArrayList는 추가한만큼 크기가 변화함
     //ArrayList는 함수를 이용해서 접근.
     
     public void addSubject(String name, int score) {
          Subject subject=new Subject();
          subject.setName(name);
          subject.setScorePoint(score);
          subjectList[index++]=subject;
          //subjectList.add(subject);
     }
     
     public void showStudentInfo() {
          int total=0;
          for(Subject s : subjectList) {
              if(s==nullbreak;
              total+=s.getScorePoint();
              System.out.println("학생 "+studentName+"의 "+s.getName()+"과목 성적은 "+s.getScorePoint()+"입니다.");
          }
          System.out.println("학생 "+studentName+"의 총점은 "+total+" 입니다.");
     }
}

 


  • 학생클래스, 버스, 지하철, 택시 클래스를 구현하여 학생이 버스나 지하철을 타고 요금을 냈을때 학생이름, 잔액, 버스 승객, 버스 수입, 지하철 승객, 지하철 수입을 출력하기 (Student, Bus, Subway, Taxi, TakeTrans)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package cooperation;
 
public class TakeTrans {
    
    public static void main(String[] args) {
        Student s1=new Student("홍길동"5000);
        Student s2=new Student("이순신"10000);
        Student s3=new Student("Edward"20000);
        
        Bus bus=new Bus(100); //100번 버스
        //s1학생이 100번 버스를 탄다.
        s1.takeBus(bus); //매개변수가 객체가 됨.
        
        Subway subway=new Subway("2호선");
        //s2학생이 2호선 지하철을 딴다.
        s2.takeSubway(subway);
        
        Taxi taxi=new Taxi("yellow");
        s3.takeTaxi(taxi);
        
        s1.showInfo();
        s2.showInfo();
        s3.showInfo();
        
        bus.showInfo();
        subway.showInfo();
        taxi.showInfo();
        
    }
}

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package cooperation;
 
public class Student { 
    private String studentName; //학생이름
    private int grade; //학년
    private int money; //학생이 가지고 있는 돈
    
    public Student(String studentName, int money) {
        this.studentName=studentName;
        this.money=money;
    }
    
    //버스타다
    public void takeBus(Bus bus) { //Bus형에 bus가 들어감. 매개변수를 객체로.
        bus.take(1000);
        this.money-=1000;
    }
    
    //지하철타다
    public void takeSubway(Subway subway) { //Subway형에 subway가 들어감.
        subway.take(1500);
        this.money-=1500;
    }
    
    public void takeTaxi(Taxi taxi) {
        taxi.take(10000);
        this.money-=10000;
    }
    
    public void showInfo() {
        System.out.println("학생 이름: "+studentName);
        System.out.println("학생 잔액: "+money);
    }
    
}
 

 

 

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

 

 

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

 


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

 

 

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

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package day07;
public class Father extends GrandFather {
     String str="아버지"//멤버변수
     
     public Father() {
          System.out.println(str+" 생성자 ");
     }
     
     public Father(String msg) {
          System.out.println(msg);
     }
     
     public void fatherPrint() {
          System.out.println("father print 메소드");
     }
     
     public void methodTest() {
          System.out.println("test method");
     }
     
     //오버라이드. (메소드 오버라이딩) 상속관계에 있어서 부모의 것을 자식이 재정의 하는 것.
     //(오버로딩: 메소드나 생성자 이름은 같은데 괄호안에 들어있는 매개변수가 달라서 다르게 접근하는 것)
     public void grandPrint() { //할아버지 메소드. 오버라이딩 됨. 할아버지가 아니라 아버지에 있는 것이 출력됨.
          System.out.println("할아버지 grandPrint 메소드를 father가 수정함");
     }
}

 

 

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

 


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

 

 

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

 


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

 

 

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

 

 

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

 

 

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

 


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

 

 

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

 

 

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

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package day07;
 
import java.util.Scanner;
 
public class ShapeMain {
    static Scanner sc=new Scanner(System.in);
    
    public static void showMenu() {
        System.out.println("선택하세요...");
        System.out.println("1.원 2.사각형 3.보기 4.종료");
        System.out.print("선택:");
    }
    
    public static void main(String[] args) {
            ShapeManager sm=new ShapeManager();
            
            while(true) {
            ShapeMain.showMenu(); 
            //클래스 이름에 static 불였으니까 ShapeMain으로 부를 수 있음.
            int num=sc.nextInt();
            switch(num) {
            case 1 : //원입력
            case 2 : sm.inputData(num); break//사각형입력
            case 3 : sm.viewData(); break//전체보기
            case 4 : System.out.println("종료");
                     System.exit(0);
            default : System.out.println("입력오류");
            }
        }
    }
}
 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package day07;
 
public class ShapeManager {
    //입력받은 좌표, 반지름, 너비, 높이 등을 저장하기 위해 배열 선언
    //부모형으로 선언을 해야 Circle, Square 모두 적용가능
    Shape[]arr=new Shape[50]; 
    int cnt;
    
    public void inputData(int num) { //원->x,y,r 사각형->x,y,w,h
        System.out.println("도형입력....");
        System.out.print("x 좌표>>");
        int x=ShapeMain.sc.nextInt();
        System.out.print("y 좌표>>");
        int y=ShapeMain.sc.nextInt();
        
        if(num==1) { //원
            System.out.print("반지름>>");
            int r=ShapeMain.sc.nextInt();
            arr[cnt++]=new Circle(x,y,r);
        }
        else if(num==2) { //사각형
            System.out.print("너비>>");
            int w=ShapeMain.sc.nextInt();
            System.out.print("높이>>");
            int h=ShapeMain.sc.nextInt();
            arr[cnt++]=new Square(x,y,w,h);
        }
    }
    
    public void viewData() {
        for(Shape s: arr) {
            if(s==nullbreak;
            s.print();
        }
    }
}

 

+ Recent posts