프로그래밍/Java
[자바/java] text파일에 저장된 단어로 행맨만들기
Rolen
2023. 2. 1. 22:10
package q11;
import java.io.*;
import java.util.*;
public class Q11 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("--경로입력--\\word.txt"));
String str;
ArrayList wordList = new ArrayList<>(); // 파일내의 모든 단어를 리스트화, 추후 랜덤으로 단어 하나 선택
Random rd = new Random();
while ((str = br.readLine()) != null) {
wordList.add(str);
}
String result = ""; // 답의 단어크기 만큼 "_"로 변환
StringBuilder builder; // result를 넣고 답이 입력되었을 때 비교하여 해당 자리 변환
str = (String) wordList.get(rd.nextInt(wordList.size()-1));
for (int i = 0; i < str.length(); i++) { result += "_"; }
builder = new StringBuilder(result);
Scanner sc = new Scanner(System.in);
int count = 0;
while (true) {
System.out.print("추측하는 글자를 입력하세요: ");
count++;
char w = sc.next().charAt(0);
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (w == c) {
builder.setCharAt(i, w);
}
}
System.out.println(builder + " / 도전횟수: " + count);
if (builder.indexOf("_") == -1) {
System.out.println("성공!");
break;
}
}
br.close();
sc.close();
}
}
728x90