Set interface 활용

ColinSong·2020년 11월 17일
0

Play

목록 보기
1/7
post-thumbnail

1. Set

Set을 자바의 정석(기초편)으로 이론을 학습하고 간단히 프로그램을 만들어
활용해보려 한다! 기억에 잘 남으라고......:>

  • Set inteface는 중복값을 허용하지 않는다.
  • 중복값이 있을 시 1개만 출력됨.

1.2 어떤 프로그램인가?

  • 학생을 입력하여, 중복된 이름이 있을 시 프로그램은 종료된다.
    • 스스로 생각해본 예제이므로 부족한 점이 있을 수 있다... 😂

2. 사용 클래스, 메서드

- SetInterface 클래스
- add() // 메서드
- print(); // 메서드
- set.add

2.1 CODE

  • SetInterface 클래스
  class SetInterface {
      Set<String> set = new HashSet<>();
      Scanner scan = new Scanner(System.in);

      public SetInterface() {
          System.out.println("추가할 학생 수를 입력해 주세요.");
          int count = scan.nextInt(); // 몇 명의 학생들을 입력할 건지 count로 받는다.
          for(int i = 0; i < count; i++) {
              add();
          }
      }

      public void add() {
          System.out.println("학생을 입력하세요.");
          String name = scan.next();
          if(set.contains(name)) { //set.contains는 boolean값을 반환함.
              System.out.println("중복입니다. ");
              return;
          }
          set.add(name); //set.add시 학생의 데이터를 쌓아준다.
      }

      public Set print() {
          for(String a : set) {
              System.out.println(a);
          }
          return set;
      }
  }
  • Application.java

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

          SetInterface s = new SetInterface();

      }
  }

프로그램

profile
안녕하세요:)

0개의 댓글