Java Practice Questions with Solutions and Code
1. Grade Calculator
-------------------
Logic: Take the user's marks, check which range they fall into, and print the appropriate grade using
if-else conditions.
Code:
import java.util.Scanner;
public class GradeCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter marks: ");
int marks = scanner.nextInt();
if (marks >= 90) {
System.out.println("Grade: A");
} else if (marks >= 80) {
System.out.println("Grade: B");
} else if (marks >= 70) {
System.out.println("Grade: C");
} else if (marks >= 60) {
System.out.println("Grade: D");
} else {
System.out.println("Grade: F");
}
2. Even and Odd Counter
------------------------
Logic: Loop through 10 numbers, use num % 2 to check if even or odd, and keep count.
Code:
import java.util.Scanner;
public class EvenOddCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int evenCount = 0, oddCount = 0;
for (int i = 1; i <= 10; i++) {
System.out.print("Enter number " + i + ": ");
int num = scanner.nextInt();
if (num % 2 == 0) {
evenCount++;
} else {
oddCount++;
System.out.println("Even numbers: " + evenCount);
System.out.println("Odd numbers: " + oddCount);
}
... (Truncated for brevity, but follows the same structure for other solutions.)