-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfilereader and exception
More file actions
131 lines (99 loc) · 3.35 KB
/
filereader and exception
File metadata and controls
131 lines (99 loc) · 3.35 KB
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
123
124
125
126
127
128
129
130
131
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
public class main {
public static void main(String[] args) {
String filePath="src\\words.txt";
ArrayList<String> words=new ArrayList<>();
try(BufferedReader reader=new BufferedReader(new FileReader(filePath))){
String line;
while((line=reader.readLine()) != null){
words.add(line.trim());
}
}
catch(FileNotFoundException e){
System.out.println("File is not found");
}
catch(IOException e){
System.out.println("Something went wrong");
}
Random random=new Random();
String word=words.get(random.nextInt(words.size()));
int wrongGuesses=0;
ArrayList<Character> wordState=new ArrayList<>();
Scanner scanner=new Scanner(System.in);
System.out.println("------------------------");
System.out.println("Welcome to Hangman Game!");
System.out.println("------------------------");
for(int i=0;i<word.length();i++){
wordState.add('_');
}
while(wrongGuesses<6){
System.out.println(getHangmanArt(wrongGuesses));
System.out.print("Word : ");
for(char c:wordState){
System.out.print(c+" ");
}
System.out.println();
System.out.print("Guess a letter : ");
char guess=scanner.next().toLowerCase().charAt(0);
if(word.indexOf(guess)>=0){
System.out.println("That is correct");
for(int i=0;i<word.length();i++){
if(word.charAt(i)==guess){
wordState.set(i,guess);
}
}
if(!wordState.contains('_')){
System.out.println("You won");
System.out.println("The word was : " +word);
break;
}
}
else{
System.out.println("That is a wrong guess");
wrongGuesses++;
}
}
if(wrongGuesses>=6){
System.out.println(getHangmanArt(wrongGuesses));
System.out.println("You lost bitch ");
System.out.println("The word was : " +word);
}
scanner.close();
}
static String getHangmanArt(int wrongGuesses){
return switch(wrongGuesses){
case 1-> """
o
""";
case 2-> """
o
/
""";
case 3-> """
o
/|
""";
case 4-> """
o
/|\\
""";
case 5-> """
o
/|\\
/
""";
case 6-> """
o
/|\\
/ \\
""";
default->"";
};
}
}