亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Core concept: do-while loop implements interactive control
User input processing and resource management
Code optimization and precautions
Summarize
Home Java javaTutorial Control program looping and exit through user input in Java

Control program looping and exit through user input in Java

Oct 12, 2025 am 06:24 AM

Control program looping and exit through user input in Java

This tutorial will guide you on how to use do-while loop structures and user input in Java programs to achieve repeated execution or graceful exit of the program. Through an interactive calculator example, we will demonstrate how to effectively handle user instructions, manage input resources, and optimize code logic to ensure that the program has a good user experience and meets robustness requirements.

Core concept: do-while loop implements interactive control

When developing interactive programs, we often need the program to perform a specific operation at least once and then decide whether to continue based on the user's selection. The do-while loop structure is ideally designed for this type of scenario. Its characteristic is that the code in the loop body is executed first, and then the loop condition is evaluated. The loop continues as long as the condition is true; it terminates when the condition is false.

For the calculator program in this tutorial, the user will need to perform at least one calculation. After the calculation is complete, the program will ask the user whether to continue (enter 1) or exit (enter 0). The do-while loop can perfectly capture this "execute first, judge later" logic. We put all the calculation logic into the do block and use the instructions entered by the user as the basis for judging the while condition.

User input processing and resource management

In Java, the java.util.Scanner class is a common tool for obtaining user input (such as keyboard input). It provides multiple methods to read different types of data, such as nextInt() for reading integers and next() for reading strings.

When dealing with user input, resource management is especially important. Scanner objects consume system resources when they are created (for example, associated with an input stream). Failure to properly close these resources can lead to resource leaks, especially in large or long-running applications. The try-with-resources statement introduced in Java 7 is the recommended way to manage such closeable resources (classes that implement the AutoCloseable interface). It ensures that the resource will be automatically closed after the try block is executed (whether it ends normally or an exception occurs), thus avoiding the tediousness and omissions of manually calling the close() method.

Here is an example of an interactive calculator that uses a do-while loop and try-with-resources to manage a Scanner:

 import java.util.InputMismatchException;
import java.util.Scanner;

public class InteractiveCalculator {

    public static void main(String[] args) {
        int command; // Used to store user instructions: 0-exit, 1-continue//Use try-with-resources to ensure that Scanner resources are automatically closed try (Scanner scanner = new Scanner(System.in)) {
            do {
                try {
                    System.out.println("Please enter the first number: ");
                    int num1 = scanner.nextInt();

                    System.out.println("Please enter the second number: ");
                    int num2 = scanner.nextInt();

                    System.out.println("Please select operation ( , -, *, /): ");
                    String operation = scanner.next();

                    System.out.print("Calculation result: ");
                    //Use switch statement to process different operators switch (operation) {
                        case " ":
                            System.out.println(num1 num2);
                            break;
                        case "-":
                            System.out.println(num1 - num2);
                            break;
                        case "*":
                            System.out.println(num1 * num2);
                            break;
                        case "/":
                            if (num2 != 0) { // Avoid divide-by-zero errors System.out.println((double) num1 / num2); // Cast to double for floating point result} else {
                                System.out.println("Error: divisor cannot be zero!");
                            }
                            break;
                        default:
                            System.out.println("Error! Invalid operator.");
                    }
                } catch (InputMismatchException e) {
                    System.out.println("Input error: Please enter a valid number.");
                    scanner.next(); // Clear incorrect input to prevent infinite loop} catch (Exception e) {
                    System.out.println("An unknown error occurred: " e.getMessage());
                }

                System.out.println("\nPlease enter '1' to continue calculation, enter '0' to exit the program:");
                // Ensure user input is an integer and handle possible non-integer input while (!scanner.hasNextInt()) {
                    System.out.println("Input error: Please enter '0' or '1'.");
                    scanner.next(); // Clear incorrect input}
                command = scanner.nextInt();

            } while (command == 1); // As long as the user enters 1, continue looping System.out.println("The program has exited.");

        } // try-with-resources will automatically close the scanner here
    }
}

Code optimization and precautions

  1. Advantages of the switch statement: When dealing with multiple equality judgments (such as different mathematical operators), the switch statement is usually clearer and more readable than a series of if-else if constructs. It can effectively organize code logic and improve maintainability.

  2. The program naturally exits: When all the code in the main method is executed, or the main method returns normally, the Java Virtual Machine (JVM) will automatically terminate the program. Therefore, in most cases, we do not need to explicitly call System.exit() to end the program. System.exit() is typically used to forcefully terminate the entire JVM from anywhere during program execution, such as when a serious error occurs or all threads need to be stopped immediately. For normal flow exits controlled by user input, it is more elegant to let the main method end naturally.

  3. Input validation and exception handling: In real applications, user input is unpredictable. To make the program more robust, we must validate user input and handle exceptions that may occur:

    • InputMismatchException : This exception is thrown when the type entered by the user does not match the type expected by the Scanner (for example, an integer was expected but a string was entered). Capturing this exception through a try-catch block and prompting the user to re-enter can effectively improve the user experience.
    • ArithmeticException : For example, in a division operation, this exception is thrown if the divisor is zero. Before performing division operation, conditional judgment (if (num2 != 0)) should be performed to avoid such errors.
    • Input validation in the loop : When obtaining the command instruction, adding a while (!scanner.hasNextInt()) loop can ensure that the user has indeed entered an integer and avoid the program crashing due to invalid input.
  4. Flexibility of loop conditions: The conditions of the while loop can be flexibly adjusted according to specific needs. For example, in addition to directly judging command == 1, you can also define a Boolean variable continueProgram = true; and then set it to false when the user chooses to exit to terminate the loop. This approach may be more readable in some complex scenarios.

Summarize

Through this tutorial, we learned how to use Java's do-while loop structure and Scanner class to implement an interactive program that allows the user to decide to continue or exit the program. We emphasized the importance of try-with-resources in resource management, as well as optimizing code logic and improving program robustness through switch statements and exception handling. Mastering these core concepts will enable you to build more user-friendly and stable Java applications.

The above is the detailed content of Control program looping and exit through user input in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to add a JAR file to the classpath in Java? How to add a JAR file to the classpath in Java? Sep 21, 2025 am 05:09 AM

Use the -cp parameter to add the JAR to the classpath, so that the JVM can load its internal classes and resources, such as java-cplibrary.jarcom.example.Main, which supports multiple JARs separated by semicolons or colons, and can also be configured through CLASSPATH environment variables or MANIFEST.MF.

How to create a file in Java How to create a file in Java Sep 21, 2025 am 03:54 AM

UseFile.createNewFile()tocreateafileonlyifitdoesn’texist,avoidingoverwriting;2.PreferFiles.createFile()fromNIO.2formodern,safefilecreationthatfailsifthefileexists;3.UseFileWriterorPrintWriterwhencreatingandimmediatelywritingcontent,withFileWriterover

Building Extensible Applications with the Java Service Provider Interface (SPI) Building Extensible Applications with the Java Service Provider Interface (SPI) Sep 21, 2025 am 03:50 AM

JavaSPI is a built-in service discovery mechanism in JDK, and implements interface-oriented dynamic expansion through ServiceLoader. 1. Define the service interface and create a file with the full name of the interface under META-INF/services/, and write the fully qualified name of the implementation class; 2. Use ServiceLoader.load() to load the implementation class, and the JVM will automatically read the configuration and instantiate it; 3. The interface contract should be clarified during design, support priority and conditional loading, and provide default implementation; 4. Application scenarios include multi-payment channel access and plug-in verification; 5. Pay attention to performance, classpath, exception isolation, thread safety and version compatibility; 6. In Java9, provide can be used in combination with module systems.

How to implement an interface in Java? How to implement an interface in Java? Sep 18, 2025 am 05:31 AM

Use the implements keyword to implement the interface. The class needs to provide specific implementations of all methods in the interface. It supports multiple interfaces and is separated by commas to ensure that the methods are public. The default and static methods after Java 8 do not need to be rewrite.

Understanding Java Generics and Wildcards Understanding Java Generics and Wildcards Sep 20, 2025 am 01:58 AM

Javagenericsprovidecompile-timetypesafetyandeliminatecastingbyallowingtypeparametersonclasses,interfaces,andmethods;wildcards(?,?extendsType,?superType)handleunknowntypeswithflexibility.1.UseunboundedwildcardwhentypeisirrelevantandonlyreadingasObject

A deep understanding of HTTP persistent connections: policies and practices for sending multiple requests on the same socket A deep understanding of HTTP persistent connections: policies and practices for sending multiple requests on the same socket Sep 21, 2025 pm 01:51 PM

This article explores in-depth the mechanism of sending multiple HTTP requests on the same TCP Socket, namely, HTTP persistent connection (Keep-Alive). The article clarifies the difference between HTTP/1.x and HTTP/2 protocols, emphasizes the importance of server-side support for persistent connections, and how to correctly handle Connection: close response headers. By analyzing common errors and providing best practices, we aim to help developers build efficient and robust HTTP clients.

Java Tutorial: How to Flatten a Nested ArrayList and Fill its Elements into an Array Java Tutorial: How to Flatten a Nested ArrayList and Fill its Elements into an Array Sep 18, 2025 am 07:24 AM

This tutorial details how to efficiently process nested ArrayLists containing other ArrayLists in Java and merge all its internal elements into a single array. The article will provide two core solutions through the flatMap operation of the Java 8 Stream API: first flattening into a list and then filling the array, and directly creating a new array to meet the needs of different scenarios.

How to get the calling method's name in Java? How to get the calling method's name in Java? Sep 24, 2025 am 06:41 AM

The answer is to use Thread.currentThread().getStackTrace() to get the call method name, and obtain the someMethod name of the call anotherMethod through index 2. Since index 0 is getStackTrace, 1 is the current method, and 2 is the caller, the example output is "Calledbymethod:someMethod", which can also be implemented by Throwable, but attention should be paid to performance, obfuscation, security and inline impact.

See all articles