Practice: Fundamentals

This lesson is the hands-on practice for Phase 1, consolidating what you've learned through 4 projects.

Project 1: Multiplication Table

Skills used: for loops, nested loops, formatted output.

Requirements

Print a complete multiplication table (1-9).

Implementation

JAVA
public class MultiplicationTable {
    public static void main(String[] args) {
        for (int i = 1; i <= 9; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.printf("%d×%d=%-4d", j, i, i * j);
            }
            System.out.println();
        }
    }
}

Output

TEXT
1×1=1
1×2=2   2×2=4
1×3=3   2×3=6   3×3=9
1×4=4   2×4=8   3×4=12  4×4=16
1×5=5   2×5=10  3×5=15  4×5=20  5×5=25
1×6=6   2×6=12  3×6=18  4×6=24  5×6=30  6×6=36
1×7=7   2×7=14  3×7=21  4×7=28  5×7=35  6×7=42  7×7=49
1×8=8   2×8=16  3×8=24  4×8=32  5×8=40  6×8=48  7×8=56  8×8=64
1×9=9   2×9=18  3×9=27  4×9=36  5×9=45  6×9=54  7×9=63  8×9=72  9×9=81

Key Concepts

Project 2: Bubble Sort

Skills used: arrays, nested loops, variable swapping.

Requirements

Sort an array in ascending order.

Implementation

JAVA
import java.util.Arrays;

public class BubbleSort {
    public static void main(String[] args) {
        int[] arr = {64, 34, 25, 12, 22, 11, 90};
        
        System.out.println("Before sorting: " + Arrays.toString(arr));
        
        // Bubble sort
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    // Swap
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        
        System.out.println("After sorting: " + Arrays.toString(arr));
    }
}

Output

TEXT
Before sorting: [64, 34, 25, 12, 22, 11, 90]
After sorting: [11, 12, 22, 25, 34, 64, 90]

Key Concepts

Project 3: Number Guessing Game

Skills used: Random, Scanner input, while loops, conditional logic.

Requirements

The program generates a random number between 1-100. The user guesses, and the program responds with "too high," "too low," or "correct."

Implementation

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

public class GuessNumber {
    public static void main(String[] args) {
        Random random = new Random();
        Scanner scanner = new Scanner(System.in);
        
        int target = random.nextInt(100) + 1;
        int guess = 0;
        int attempts = 0;
        
        System.out.println("=== Number Guessing Game ===");
        System.out.println("I'm thinking of a number between 1-100. Guess it!");
        
        while (guess != target) {
            System.out.print("Enter your guess: ");
            guess = scanner.nextInt();
            attempts++;
            
            if (guess > target) {
                System.out.println("Too high! Try again.");
            } else if (guess < target) {
                System.out.println("Too low! Try again.");
            } else {
                System.out.println("Congratulations! The answer is " + target);
                System.out.println("You guessed it in " + attempts + " attempts");
            }
        }
        
        scanner.close();
    }
}

Example Output

TEXT
=== Number Guessing Game ===
I'm thinking of a number between 1-100. Guess it!
Enter your guess: 50
Too high! Try again.
Enter your guess: 25
Too low! Try again.
Enter your guess: 37
Too high! Try again.
Enter your guess: 31
Congratulations! The answer is 31
You guessed it in 4 attempts
▶ Try it Yourself

Key Concepts

Project 4: Simple Calculator

Skills used: Scanner input, switch statement, arithmetic operations.

Requirements

The user inputs two numbers and an operator, and the program calculates and displays the result.

Implementation

JAVA
import java.util.Scanner;

public class Calculator {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        System.out.println("=== Simple Calculator ===");
        
        System.out.print("Enter first number: ");
        double num1 = scanner.nextDouble();
        
        System.out.print("Enter operator (+ - * /): ");
        char operator = scanner.next().charAt(0);
        
        System.out.print("Enter second number: ");
        double num2 = scanner.nextDouble();
        
        double result = 0;
        boolean valid = true;
        
        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: Cannot divide by zero");
                    valid = false;
                }
                break;
            default:
                System.out.println("Error: Unsupported operator '" + operator + "'");
                valid = false;
        }
        
        if (valid) {
            System.out.printf("%.2f %c %.2f = %.2f%n", num1, operator, num2, result);
        }
        
        scanner.close();
    }
}

Example Output

TEXT
=== Simple Calculator ===
Enter first number: 10
Enter operator (+ - * /): *
Enter second number: 5
10.00 * 5.00 = 50.00
▶ Try it Yourself

Key Concepts

Additional Practice

Exercise 1: Score Statistics

Input 10 scores and calculate the average, highest, and lowest.

JAVA
import java.util.Scanner;
import java.util.Arrays;

public class ScoreStats {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int[] scores = new int[10];
        
        // Input scores
        for (int i = 0; i < scores.length; i++) {
            System.out.print("Enter score " + (i + 1) + ": ");
            scores[i] = scanner.nextInt();
        }
        
        // Calculate statistics
        int sum = 0, max = scores[0], min = scores[0];
        for (int score : scores) {
            sum += score;
            if (score > max) max = score;
            if (score < min) min = score;
        }
        double avg = (double) sum / scores.length;
        
        // Display results
        System.out.println("\n=== Statistics ===");
        System.out.println("Scores: " + Arrays.toString(scores));
        System.out.printf("Average: %.1f%n", avg);
        System.out.println("Highest: " + max);
        System.out.println("Lowest: " + min);
        
        scanner.close();
    }
}

❓ Frequently Asked Questions

Q What if I can't figure out the project?
A Start by analyzing the requirements, think through the logic, then reference the code. Don't just copy—understand what each line does.
Q The code runs but the result is wrong?
A Use System.out.println() to print intermediate variables and check each step of the calculation.
Q How do I improve my programming skills?
A Practice more. Start with simple projects and gradually increase the difficulty.

📖 Summary

📝 Exercises

  1. Improve the calculator: Add modulus operation and support for continuous calculations
  2. Array operations: Input 10 numbers and find the prime numbers among them
  3. Improve the guessing game: Limit attempts to 7 and show guess history

Next Lesson

In the next lesson, we'll move to Phase 2 and learn about Method Basics — how to define and use methods.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏