search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Requirements analysis and problem overview
Implementation method one: String conversion method
logical steps
Sample code
Implementation method two: mathematical operation method
Advantages and Disadvantages
Notes and Summary
Home Java javaTutorial Java tutorial: Implement digital sequence filtering and specified length output

Java tutorial: Implement digital sequence filtering and specified length output

Jan 01, 2026 am 10:18 AM

Java tutorial: Implement digital sequence filtering and specified length output

This tutorial aims to guide developers how to use the Java programming language to generate a number sequence starting from 1 based on the specified number `n` input by the user. This sequence will strictly exclude all integers containing the number '1' and ensure that the final number of output numbers is exactly `n`. The article will introduce two core implementation methods: a simple solution based on string conversion and an efficient solution based on mathematical operations, and provide detailed code examples and logical analysis.

Requirements analysis and problem overview

In programming practice, we often encounter scenarios where we need to filter and process digital sequences. This tutorial focuses on a specific problem: the user inputs an integer n, and the program needs to find the number in increments starting from 1. If a number contains the number '1' (such as 1, 10, 121, etc.), then skip the number; otherwise, add it to the output sequence. This process continues until the output sequence contains n numbers that meet the conditions. The final number of numbers output must exactly match the value of n entered by the user.

For example, if the user enters 22, the program should output a sequence of 22 numbers, none of which contain '1', in ascending order. The output may be: 2, 3, 4, 5, 6, 7, 8, 9, 20, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35.

Implementation method one: String conversion method

The core idea of ​​this method is to convert each integer to be checked into a string, and then use the contains() method of the string to determine whether it contains the character '1'.

logical steps

  1. Get user input: Use the Scanner class to get the integer n input by the user.
  2. Initialize counter: Set a counter count to record the number of numbers that have been output that meet the conditions. The initial value is 0.
  3. Loop iteration: Use a for loop, starting from i = 1 and incrementing, and the loop condition is count
  4. Checking numbers: Inside the loop, convert the current number i to a string String.valueOf(i).
  5. Determine whether it contains '1': Use String.valueOf(i).contains("1") to determine whether the string contains '1'.
  6. Skip or output:
    • If '1' is included, use the continue statement to skip the remainder of the current loop and go directly to the next iteration.
    • If it does not contain '1', print the number i and increase count by 1.
  7. Close the resource: Close the Scanner object when the program ends.

Sample code

 import java.util.Scanner;

public class NumberFilterString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter an integer n:");
        int num = sc.nextInt(); // Get the n entered by the user

        int count = 0; // Initialize the counter of the output numbers System.out.println("The qualified number sequence is as follows:");

        // Loop to find and output n qualified numbers for (int i = 1; count <h4> Advantages and Disadvantages</h4>
  • Advantages: The code is concise and easy to understand, and it uses Java's built-in string processing function to achieve intuitive implementation.
  • Disadvantages: Each iteration requires an integer-to-string conversion, which may cause some performance overhead when dealing with large numbers.

Implementation method two: mathematical operation method

In order to avoid the performance loss caused by string conversion, we can use pure mathematical operations to check whether a number contains '1'. This method checks each bit of the number by repeatedly taking modulo and dividing.

logical steps

  1. Obtain user input and initialize counter: same as method one.
  2. Loop iteration: Same as method one.
  3. Checking numbers (mathematically): Inside the loop, for the current number i, create a temporary variable val = i.
    • Use a while loop to continue as long as val > 0.
    • Inside the while loop, get the single digit of val through val % 10.
    • If the ones digit is '1', a boolean flag hasOne = true is set, and the inner while loop is immediately broken out, since it has been determined that the number contains '1'.
    • Otherwise, remove the single digit by val = val / 10 and continue checking the next digit.
  4. Skip or output:
    • If hasOne is true, use the continue statement to skip the remainder of the current outer for loop.
    • If hasOne is false (meaning the number does not contain '1'), print the number i and increase count by 1.
  5. Close the resource: Close the Scanner object when the program ends.

Sample code

 import java.util.Scanner;

public class NumberFilterMath {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter an integer n:");
        int num = sc.nextInt(); // Get the n entered by the user

        int count = 0; // Initialize the counter of the output numbers System.out.println("The qualified number sequence is as follows:");

        // Loop to find and output n qualified numbers for (int i = 1; count  0) {
                if (val % 10 == 1) { // If the current bit is '1'
                    hasOne = true; // Set the flag break; // Stop checking after finding '1'}
                val = val / 10; // remove current bit, check next bit}

            if (hasOne) {
                continue; // If it contains '1', skip the current number}
            System.out.print(i " "); // Output the number count that meets the conditions; // Add 1 to the counter
        }
        System.out.println("\nA total of " count " numbers were output.");
        sc.close(); // Close Scanner
    }
}

Advantages and Disadvantages

  • Advantages: Avoids the overhead of string conversion, which may be more efficient for processing very large numbers or scenarios that require high performance.
  • Disadvantages: The logic is slightly more complicated than string conversion and requires an inner while loop to process each bit.

Notes and Summary

  1. Loop condition: Both methods use a loop structure such as for (int i = 1; count
  2. continue keyword: The continue statement plays an important role here. It allows the program to skip the remaining code of the current loop and directly enter the next iteration when it finds a number that does not meet the conditions, thus avoiding unnecessary processing.
  3. Input and Output: Ensure that the program receives user input correctly and outputs the results in a clear format. In practical applications, you can consider storing the output numbers in a list instead of printing them directly for subsequent processing.
  4. Resource management: After using the Scanner object, be sure to call sc.close() to close the resource to prevent resource leakage.

In summary, developers can choose a suitable implementation method based on specific needs. If you pursue code simplicity and readability, and do not have extreme performance requirements, the string conversion method is a good choice. If you need to process a large amount of data and have high performance requirements, then mathematical algorithms will be a better solution. Understanding the core logic of these two methods will help you flexibly deal with similar problems in different scenarios.

The above is the detailed content of Java tutorial: Implement digital sequence filtering and specified length output. 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

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude 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

Popular tool

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)

How to configure Spark distributed computing environment in Java_Java big data processing How to configure Spark distributed computing environment in Java_Java big data processing Mar 09, 2026 pm 08:45 PM

Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre

How to safely map user-entered weekday string to integer value and implement date offset operation in Java How to safely map user-entered weekday string to integer value and implement date offset operation in Java Mar 09, 2026 pm 09:43 PM

This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.

How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips Mar 06, 2026 am 06:24 AM

Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.

How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers Mar 09, 2026 pm 09:48 PM

Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.

What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling Mar 10, 2026 pm 06:57 PM

What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-

How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) How to correctly implement runtime file writing in Java applications (avoiding JAR internal write failures) Mar 09, 2026 pm 07:57 PM

After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).

What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis Mar 09, 2026 pm 09:45 PM

ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.

How to safely read a line of integer input in Java and avoid Scanner blocking How to safely read a line of integer input in Java and avoid Scanner blocking Mar 06, 2026 am 06:21 AM

This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.

Related articles