Practice Day: Build a simple CLI calculator or quiz

Practice Java basics by building a CLI calculator or quiz using user input, operators, and conditionals. Day 7 Java tutorial for beginners."
Practice Day: Build a simple CLI calculator or quiz

On Day 7, it’s time to practice! By now, you have learned variables, data types, operators, conditional statements, and how to take user input. Today, you will apply all these concepts in a small project. Choose one of the following exercises:

1. Simple CLI Calculator

This calculator uses Scanner for input, arithmetic operators for calculations, and switch for decision-making.


import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter first number: ");
        double num1 = scanner.nextDouble();

        System.out.print("Enter second number: ");
        double num2 = scanner.nextDouble();

        System.out.print("Choose operation (+, -, *, /): ");
        char operator = scanner.next().charAt(0);

        double result;

        switch (operator) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num1 - num2;
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                if (num2 != 0) {
                    result = num1 / num2;
                } else {
                    System.out.println("Error: Division by zero");
                    return;
                }
                break;
            default:
                System.out.println("Invalid operator");
                return;
        }

        System.out.println("Result: " + result);
    }
}

2. Simple CLI Quiz

This quiz uses if-else statements and String comparison.


import java.util.Scanner;

public class Quiz {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int score = 0;

        System.out.println("Q1: What is the capital of France?");
        String answer1 = scanner.nextLine();
        if (answer1.equalsIgnoreCase("Paris")) {
            score++;
        }

        System.out.println("Q2: What is 5 + 3?");
        int answer2 = scanner.nextInt();
        if (answer2 == 8) {
            score++;
        }

        System.out.println("You scored " + score + " out of 2");
    }
}

Summary

Both exercises combine all the concepts you’ve learned so far. The calculator focuses on operators and switch, while the quiz emphasizes Strings, conditionals, and user input. Try building both to strengthen your Java skills!

Post a Comment