문자열 토큰 분리

Jane·2023년 2월 16일
0

IT 수업 정리

목록 보기
44/124

문제

1.아래를 프로그래밍 하시오.
Scanner를 이용하여 한 라인을 읽고,
공백으로 분리된 어절이 몇 개인지 출력을 반복하는
프로그램을 작성하라. “exit”이 입력되면 종료한다.

단)stringTokenizer 활용
try catch 구문 넣으시오.

코드

import java.util.Scanner;
import java.util.StringTokenizer;

class Game {
	private String str;

	public Game(String str) {
		this.str = str;
	}

	public void play() {

		StringTokenizer st = new StringTokenizer(this.str, " ");
		int count = 0;

		while (st.hasMoreTokens()) {
			System.out.println(st.nextToken() + ' ');
			count++;
		}

		System.out.println(count + "개의 단어입니다.");
		check();

	}

	public void check() {
		System.out.println("계속 하시겠습니까? :: exit을 넣으면 종료");
		Scanner sc = new Scanner(System.in);
		String yn = sc.nextLine();
		if (yn.equals("exit")) {
			System.out.println("종료합니다.");
			System.exit(0);
		}

	}
}

class JavaTest {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		try {
			while (true) {
				System.out.print("문자열을 입력하세요. : ");
				String str = sc.nextLine();
				
					Game g = new Game(str);
					g.play();
				
			}
		}catch(Exception e) {
			e.getMessage();
		}
	}

}
profile
velog, GitHub, Notion 등에 작업물을 정리하고 있습니다.

0개의 댓글