Java from beginner to proficient - process control (2)

Exercise explanation:


Last time we left you with some process control issues. This time we will analyze and explain them to you:


Conditional statement exercises:

1. Write a Java program to accept the number input by the user, then determine whether it is an even number or an odd number, and output the corresponding message.

import java.util.Scanner;

public class OddEvenCheck {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);
        
        // 提示用户输入一个整数
        System.out.print("请输入一个整数: ");
        
        // 从用户输入中读取整数
        int number = scanner.nextInt();
        
        // 使用条件语句判断数字是偶数还是奇数
        if (number % 2 == 0) {
            System.out.println(number + " 是偶数。");
        } else {
            System.out.println(number + " 是奇数。");
        }
        
        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses to be able to read data from user input.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Use System.out.printa statement to prompt the user for an integer.

  4. Use to scanner.nextInt()read an integer from the user's input and store it in numbera variable.

  5. Use a conditional statement ifto check numberif it is an even number. If numberthe remainder after dividing by 2 is equal to 0, then it is an even number, otherwise it is an odd number.

  6. Based on the judgment result, the program will output a corresponding message to tell the user whether the entered number is even or odd.

  7. Finally, we use scanner.close()to close Scannerthe object to release resources.

Summary of example questions:

This program demonstrates how to use conditional statements to determine whether a number entered by the user is even or odd. It first accepts user input and then uses a conditional expression to check if the entered number is divisible by 2. If it can, it is considered an even number, otherwise it is considered an odd number, and the appropriate message is output. This example emphasizes the use of conditional statements in Java, which is one of the foundations of programming.

2. Create a simple login system that requires users to enter a username and password. If the username is "admin" and the password is "password", a welcome message is displayed, otherwise an error message is displayed.

import java.util.Scanner;

public class SimpleLoginSystem {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入用户名
        System.out.print("请输入用户名: ");
        String username = scanner.nextLine();

        // 提示用户输入密码
        System.out.print("请输入密码: ");
        String password = scanner.nextLine();

        // 验证用户名和密码
        if (username.equals("admin") && password.equals("password")) {
            System.out.println("欢迎 " + username + " 进入系统!");
        } else {
            System.out.println("用户名或密码错误,请重试。");
        }

        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses to be able to read data from user input.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Use System.out.printa statement to prompt the user for a username.

  4. Use to scanner.nextLine()read the username from the user's input and store it in usernamea variable.

  5. Prompts the user for a password.

  6. Use to scanner.nextLine()read the password from the user's input and store it in passworda variable.

  7. Use conditional statements ifto verify that the username and password match. If the username is "admin" and the password is "password", a welcome message is displayed; otherwise, an error message is displayed.

  8. Finally, we use scanner.close()to close Scannerthe object to release resources.

Summary of example questions:

This program demonstrates how to create a simple login system that requires the user to enter a username and password, and validates this information. It uses conditional statements to check if the username and password match, if so it displays a welcome message, otherwise it displays an error message. This example highlights conditional statements and handling of user input in Java. In real applications, security requires more complex processing, but this example provides a basic framework.

3. Write a program that accepts the year input by the user, then determines whether the year is a leap year, and outputs the corresponding message. Leap year conditions: Divisible by 4 but not 100, or divisible by 400.

import java.util.Scanner;

public class LeapYearCheck {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);

        // 提示用户输入一个年份
        System.out.print("请输入一个年份: ");
        int year = scanner.nextInt();

        // 使用条件语句判断是否为闰年
        if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
            System.out.println(year + " 是闰年。");
        } else {
            System.out.println(year + " 不是闰年。");
        }

        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses to be able to read data from user input.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Use System.out.printa statement to prompt the user for a year.

  4. Use to scanner.nextInt()read the year from the user's input and store it in yeara variable.

  5. Use a conditional statement ifto determine whether the year is a leap year. Depending on the leap year condition, we check two conditions: the year is divisible by 4 but not 100, or it is divisible by 400. If either of the two conditions is met, it is considered a leap year.

  6. Based on the judgment result, the program will output a corresponding message to tell the user whether the input year is a leap year or not.

  7. Finally, we use scanner.close()to close Scannerthe object to release resources.

Summary of example questions:

This program demonstrates how to accept a user-entered year and use a conditional statement to determine if it is a leap year. It checks two conditions to determine the leap year status of the year based on the definition of leap year, and outputs the appropriate message. This example emphasizes the use of conditional statements in Java, which is one of the foundations of programming.

Loop statement exercises:

4. Use  for a loop to print out all odd numbers from 1 to 100.

public class PrintOddNumbers {
    public static void main(String[] args) {
        // 使用for循环遍历1到100的所有数字
        for (int i = 1; i <= 100; i++) {
            // 检查是否是奇数
            if (i % 2 != 0) {
                // 如果是奇数,就打印出来
                System.out.println(i);
            }
        }
    }
}

Analysis and explanation:

  1. We use  for a loop to iterate through all the numbers from 1 to 100,  i initializing it to 1 and then incrementing it by 1 after each iteration.

  2. In each iteration of the loop, we use a conditional statement  if to check if the current number  i is odd.

  3. If  i it is not divisible by 2 ( i % 2 != 0 i.e. true), then it is an odd number.

  4. If  i it's an odd number, we just  System.out.println(i); print it out.

Summary of example questions:

This program will loop through the numbers from 1 to 100 and print out only odd numbers, i.e. numbers that are not divisible by 2. This is a common usage for filtering and processing specific types of numbers.

5. Use  while a loop to find all the factors of a positive integer

import java.util.Scanner;

public class FactorsOfNumber {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);
        
        // 提示用户输入一个正整数
        System.out.print("请输入一个正整数: ");
        int number = scanner.nextInt();
        
        // 初始化一个除数
        int divisor = 1;
        
        // 使用while循环找出所有因子
        System.out.print(number + " 的因子包括: ");
        while (divisor <= number) {
            if (number % divisor == 0) {
                System.out.print(divisor + " ");
            }
            divisor++;
        }
        
        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses to be able to read data from user input.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Use System.out.printa statement to prompt the user for a positive integer.

  4. Use to scanner.nextInt()read a positive integer from the user's input and store it in numbera variable.

  5. Initialize a divisor  divisor, starting with 1.

  6. Use  while a loop to find  number the factors. In each iteration, we check whether  number it is  divisor divisible. If it is divisible, it means  divisor it is a factor and prints it out.

  7. After each iteration, we increment  divisor the value and continue looking for the next factor.

  8. Finally, we use scanner.close()to close Scannerthe object to release resources.

Summary of example questions:

This program will find all the factors of a positive integer entered by the user and print them out. This is a common method of finding factors and can be used in mathematical and algorithmic problems.

6. Use  do...while a loop to implement a number guessing game. The program randomly generates a number and then prompts the user to guess the number until the user guesses correctly.

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

public class GuessNumberGame {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);
        // 创建一个Random对象来生成随机数字
        Random random = new Random();
        
        // 生成随机数字(1到100之间)
        int target = random.nextInt(100) + 1;
        int attempts = 0; // 记录尝试次数
        int guess; // 用户猜的数字

        do {
            System.out.print("猜一个1到100之间的数字: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess < target) {
                System.out.println("太小了,请再试一次。");
            } else if (guess > target) {
                System.out.println("太大了,请再试一次。");
            }
        } while (guess != target);

        System.out.println("恭喜,你猜对了!总共尝试了 " + attempts + " 次。");

        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses and java.util.Randomclasses to be able to read data from user input and generate random numbers.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Create an Randomobject that generates a random target number (between 1 and 100).

  4. Use  do...while a loop to implement a guessing game. The game will continue until the user guesses correctly.

  5. On each iteration of the loop, the program prompts the user for a guessed number and stores it in guessa variable. At the same time, attemptsthe variable records the number of attempts made by the user.

  6. The program checks whether the user's guess is correct. If the guess is less than the target number, "Too small, please try again." is displayed; if the guess is greater than the target number, "Too big, please try again." is displayed.

  7. When the user guesses the number correctly ( guess == target), the loop ends and a congratulations message is output, showing that the user guessed correctly and telling them the number of attempts.

  8. Finally, we use scanner.close()to close Scannerthe object to release resources.

Summary of example questions:

This program implements a simple guessing game where the user can try multiple guesses until they guess the target number. This game can be do...whileused to practice using loops and conditional statements.

Loop control statement exercises:

7. Use  break statements to improve the number guessing game above. If the user guesses incorrectly 5 times in a row, the game will automatically end.

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

public class ImprovedGuessNumberGame {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);
        // 创建一个Random对象来生成随机数字
        Random random = new Random();

        // 生成随机数字(1到100之间)
        int target = random.nextInt(100) + 1;
        int attempts = 0; // 记录尝试次数
        int guess; // 用户猜的数字

        while (true) {
            System.out.print("猜一个1到100之间的数字: ");
            guess = scanner.nextInt();
            attempts++;

            if (guess < target) {
                System.out.println("太小了,请再试一次。");
            } else if (guess > target) {
                System.out.println("太大了,请再试一次。");
            } else {
                System.out.println("恭喜,你猜对了!总共尝试了 " + attempts + " 次。");
                break; // 用户猜对,结束游戏
            }

            if (attempts >= 5) {
                System.out.println("你已经尝试了5次,游戏结束。");
                break; // 用户连续猜错5次,结束游戏
            }
        }

        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. This program is similar to the previous number-guessing game program, but uses a  while (true) loop to automatically end the game after the user guesses incorrectly five times in a row.

  2. In each loop, the program checks whether the user's guess is correct. If the guess is less than the target number, "Too small, please try again." is displayed; if the guess is greater than the target number, "Too big, please try again." is displayed.

  3. If the user guesses the number ( guess == target) correctly, the program will output a congratulations message and display the number of user attempts, and then use  break the statement to end the game loop.

  4. If the user guesses incorrectly 5 times in a row ( attempts >= 5), the program will output a message and use  break the statement to end the game loop and end the game.

Summary of example questions:

This program allows the user to guess numbers and automatically ends the game after the user guesses incorrectly 5 times in a row. This improvement can increase the interactivity and challenge of the game.

8.  continue Write a program using statements to print out all numbers from 1 to 100, but skip all numbers containing the number 7, for example, skip 7, 17, 27…

public class PrintNumbersSkipSeven {
    public static void main(String[] args) {
        // 使用for循环遍历1到100的所有数字
        for (int i = 1; i <= 100; i++) {
            // 检查是否包含数字7
            if (containsSeven(i)) {
                continue; // 跳过包含数字7的数字
            }
            // 打印当前数字
            System.out.println(i);
        }
    }

    // 辅助函数:检查一个数字是否包含数字7
    private static boolean containsSeven(int number) {
        while (number > 0) {
            int digit = number % 10;
            if (digit == 7) {
                return true; // 包含数字7
            }
            number /= 10;
        }
        return false; // 不包含数字7
    }
}

Analysis and explanation:

  1. This program uses  for a loop to iterate through all numbers from 1 to 100,  i initializing it to 1 and then incrementing it by 1 after each iteration.

  2. In each iteration of the loop, the program uses  containsSeven(i) a function to check whether the current number  i contains the number 7.

  3. containsSeven Function is used to check whether a number contains the number 7. It checks whether each digit is 7 by repeatedly taking the single digits of the number and then dividing the number by 10.

  4. If  containsSeven(i) it returns  true, use  continue the statement to skip the numbers containing the number 7 and continue with the next number.

  5. If the number 7 is not included, print  System.out.println(i); the current number.

Summary of example questions:

This program will print out all numbers from 1 to 100, but will skip numbers containing the number 7. This is a common practice to skip certain iterations under certain conditions.

9. Create a simple menu program that lets the user select different options (e.g., 1. Add new item, 2. View item, 3. Exit program). Use  switch statements to handle user choices

import java.util.Scanner;

public class SimpleMenu {
    public static void main(String[] args) {
        // 创建一个Scanner对象来接受用户输入
        Scanner scanner = new Scanner(System.in);
        int choice;

        do {
            // 显示菜单选项
            System.out.println("菜单:");
            System.out.println("1. 添加新项目");
            System.out.println("2. 查看项目");
            System.out.println("3. 退出程序");
            System.out.print("请选择选项(1/2/3): ");
            
            // 读取用户选择
            choice = scanner.nextInt();

            // 使用switch语句处理用户选择
            switch (choice) {
                case 1:
                    System.out.println("选项1:添加新项目");
                    // 在这里添加处理添加新项目的代码
                    break;
                case 2:
                    System.out.println("选项2:查看项目");
                    // 在这里添加处理查看项目的代码
                    break;
                case 3:
                    System.out.println("选项3:退出程序");
                    break;
                default:
                    System.out.println("无效的选项,请重新选择。");
            }
        } while (choice != 3); // 当用户选择退出时结束循环

        // 关闭Scanner对象
        scanner.close();
    }
}

Analysis and explanation:

  1. We first import java.util.Scannerclasses to be able to read data from user input.

  2. Create an Scannerobject that will help us accept input from the user.

  3. Use  do...while a loop to implement a menu program that will run until the user chooses to exit.

  4. During each iteration of the loop, the program displays menu options and prompts the user for selection.

  5. Use to scanner.nextInt()read the user's selection and store it in choicea variable.

  6. Use switchstatements to handle user choices. caseDepending on the options, you can add processing code in the corresponding branch.

  7. If the user chooses to exit ( choice == 3), the loop ends and the program exits.

Summary of example questions:

This program demonstrates how to create a simple menu system that allows the user to select different options and use a `switch` statement to process these options. You can extend the functionality of each option as needed.

Guess you like

Origin blog.csdn.net/m0_53918860/article/details/132741560