Skip to content

Latest commit

 

History

History
91 lines (69 loc) · 2.57 KB

8.md

File metadata and controls

91 lines (69 loc) · 2.57 KB

Basic Projects

In this lesson, we will work on some basic projects to apply the concepts we have learned so far.

Creating a Simple Calculator

Let's create a simple calculator program that takes in two numbers and an operator (+, -, *, /) as input and performs the corresponding operation.

import java.util.Scanner;

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

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

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

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

        double result = 0;

        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("Error: Invalid operator!");
                return;
        }

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

Building a Basic Game

Let's create a simple guessing game where the user has to guess a randomly generated number between 1 and 100.

import java.util.Random;
import java.util.Scanner;

public class GuessingGame {
    public static void main(String[] args) {
        Random random = new Random();
        int secretNumber = random.nextInt(100) + 1;

        Scanner scanner = new Scanner(System.in);

        int guess;
        do {
            System.out.print("Guess a number between 1 and 100: ");
            guess = scanner.nextInt();

            if (guess < secretNumber) {
                System.out.println("Too low! Try again.");
            } else if (guess > secretNumber) {
                System.out.println("Too high! Try again.");
            }
        } while (guess != secretNumber);

        System.out.println("Congratulations! You guessed the correct number: " + secretNumber);
    }
}

These projects demonstrate how to apply the concepts we have learned so far to create useful and interactive programs.


<< Previous | Home | Next >>