Duck Number

Check whether a number is a duck number (contains zero, but not at the first position).

IntermediateTopic: Module 3: Loop Programs
Back

Java Duck Number Program

This program helps you to learn the fundamental structure and syntax of Java programming.

Try This Code
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String s = sc.nextLine();

        boolean isDuck = false;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == '0') {
                isDuck = true;
                break;
            }
        }

        if (isDuck && s.charAt(0) != '0') {
            System.out.println(s + " is a Duck Number");
        } else {
            System.out.println(s + " is not a Duck Number");
        }
        sc.close();
    }
}
Output
Enter a number: 1023
1023 is a Duck Number

Understanding Duck Number

We work with the string form, ensuring the first digit is not zero and some later digit is zero.

Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.

Table of Contents