forked from TimSongCoder/LearnJavaForAndroid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJavaQuiz.java
More file actions
64 lines (58 loc) · 1.89 KB
/
Copy pathJavaQuiz.java
File metadata and controls
64 lines (58 loc) · 1.89 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
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.IOException;
public class JavaQuiz{
public static void main(String[] args){
List<QuizEntry> quizList = new ArrayList<QuizEntry>();
quizList.add(new QuizEntry("What's the latest version of JDK?",
new String[]{"1.8", "1.7", "1.6", "1.9"},
'A'));
quizList.add(new QuizEntry("How many primitive types does Java have?",
new String[]{"4", "8", "6", "9"},
'B'));
quizList.add(new QuizEntry("What are you learning Java for?",
new String[]{"Hobby", "Java Development", "Android Development", "Make a living"},
'C'));
Iterator<QuizEntry> iterator = quizList.iterator();
while(iterator.hasNext()){
QuizEntry quizEntry = iterator.next();
System.out.println(quizEntry.question);
for(int i=0;i<quizEntry.answers.length; i++){
System.out.println(QuizEntry.answerIndicator[i] + ". " + quizEntry.answers[i]);
}
// prompt the user to answer
System.out.print("Enter your answer: ");
try{
int userAnswer = -1;
do{
userAnswer = System.in.read();
if(!isEscapeCharacter(userAnswer)){
if(userAnswer == quizEntry.answer){
System.out.println("Congratunations, you are right.");
}else {
System.out.println("You are wrong.");
}
System.out.println();
}
}while(isEscapeCharacter(userAnswer)); // Consume the system related carrige return character.
}catch(IOException ioe){
ioe.printStackTrace();
}
}
}
static boolean isEscapeCharacter(int character){
return character == '\r' || character=='\n';
}
}
class QuizEntry{
String question;
String[] answers;
char answer;
static final char[] answerIndicator = {'A', 'B', 'C', 'D'};
QuizEntry(String question, String[] answers, char answer){
this.question = question;
this.answers = answers;
this.answer = answer;
}
}