FAQ | This is a LIVE service | Changelog

Skip to content
Snippets Groups Projects
Commit 61b43692 authored by Andrew Rice's avatar Andrew Rice
Browse files

Code demos from Lecture 3

parent 40ac7d2e
No related branches found
No related tags found
No related merge requests found
package uk.ac.cam.acr31.oop.democode1920.complicated;
import java.util.Date;
public class BadDate {
public static void main(String[] args) {
// Current date: 2019-11-13 11:00
Date d = new Date(2019, 11, 13, 11, 0);
System.out.println(d);
}
}
package uk.ac.cam.acr31.oop.democode1920.lecture3;
import java.util.ArrayList;
import java.util.List;
public class MultipleChoiceQuestion {
private final String prompt;
private final List<String> choices;
private final int correct;
public MultipleChoiceQuestion(String prompt, List<String> choices, int correct) {
this.prompt = prompt;
this.choices = new ArrayList<>(choices);
this.correct = correct;
}
void ask() {
System.out.println(prompt);
int i = 0;
for (String choice : choices) {
System.out.println(i + " " + choice);
}
}
boolean check(String response) {
int r = Integer.parseInt(response);
return r == correct;
}
}
package uk.ac.cam.acr31.oop.democode1920.lecture3;
public class PrivateDemo {
private int x;
void add(PrivateDemo p) {
p.x = 6;
}
}
package uk.ac.cam.acr31.oop.democode1920.lecture3;
public class Question {
private final String prompt;
private final String solution;
public Question(String prompt, String answer) {
this.prompt = prompt;
this.solution = answer;
}
public void ask() {
System.out.println(prompt);
}
public boolean check(String solution) {
return this.solution.equals(solution);
}
String getPrompt() {
return prompt;
}
}
package uk.ac.cam.acr31.oop.democode1920.lecture3;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Quiz {
void doQuiz() {
List<String> choices = new ArrayList<>(List.of("one", "two", "three"));
MultipleChoiceQuestion q = new MultipleChoiceQuestion("p", choices, 1);
choices.set(1, "hahaha!");
List<Question> questions =
List.of(
new Question("Should I indent source code with tabs or spaces?", "tabs"),
new Question("Which is the best college?", "mine"));
Scanner scanner = new Scanner(System.in);
int correct = 0;
for (Question question : questions) {
question.ask();
String response = scanner.nextLine();
if (question.check(response)) {
correct++;
}
}
System.out.printf("You got %d correct %n", correct);
}
public static void main(String[] args) {
Quiz quiz = new Quiz();
quiz.doQuiz();
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment