how to make quiz with arraylist in java with input character

www.l‮c.iruttua‬om
how to make quiz with arraylist in java with input character

To create a quiz with an array list in Java that accepts character input, you can use a Scanner object to read the user's input and an ArrayList to store the quiz questions and answers.

Here is an example of how you can create a quiz with an array list in Java that accepts character input:

import java.util.ArrayList;
import java.util.Scanner;

class Quiz {
    ArrayList<Question> questions = new ArrayList<>();
    
    public void addQuestion(Question question) {
        questions.add(question);
    }
    
    public void takeQuiz() {
        Scanner scanner = new Scanner(System.in);
        int score = 0;
        for (Question question : questions) {
            System.out.println(question.prompt);
            char response = scanner.nextLine().charAt(0);
            if (question.checkAnswer(response)) {
                score++;
            }
        }
        System.out.println("You got " + score + " out of " + questions.size() + " questions correct.");
    }
}

class Question {
    String prompt;
    char answer;
    
    public Question(String prompt, char answer) {
        this.prompt = prompt;
        this.answer = answer;
    }
    
    public boolean checkAnswer(char response) {
        return response == answer;
    }
}

Quiz quiz = new Quiz();
quiz.addQuestion(new Question("What is the capital of France?", 'P'));
quiz.addQuestion(new Question("What is the largest planet in the solar system?", 'J'));
quiz.takeQuiz();

In this example, a Quiz class is defined that has an ArrayList of Question objects. The Quiz class has an addQuestion method that adds a question to the array list, and a takeQuiz method that prompts the user for answers to the quiz questions and checks the answers against the correct answers.

The Question class represents a quiz question and has a prompt and an answer. The Question class has a checkAnswer method that checks if the user's response is correct.

Created Time:2017-11-01 20:42:57  Author:lautturi