In this lesson, we will work on some basic projects to apply the concepts we have learned so far.
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);
}
}
In this example, we use the Scanner
class to get input from the user. We ask for two numbers and an operator. Then, we use a switch
statement to perform the correct operation based on the operator. Finally, we print the result.
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);
}
}
In this example, we use the Random
class to generate a random number between 1 and 100. The user keeps guessing until they find the correct number. We give hints if the guess is too low or too high.
These projects demonstrate how to apply the concepts we have learned so far to create useful and interactive programs.
<< Previous | Home | Next >>