Google News
logo
Java Program to Duck Number
A Duck number is a positive number that has zeroes present in it but does not start with any zeroes. In other words, it is a number that can be represented as a non-zero number with one or more zeroes after it.

Here's a Java program to check if a number is a Duck number or not :
Program :
import java.util.Scanner;

public class DuckNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
        String input = sc.next();
        boolean isDuck = false;
        
        if(input.charAt(0) != '0') {
            for(int i=1; i<input.length(); i++) {
                if(input.charAt(i) == '0') {
                    isDuck = true;
                    break;
                }
            }
        }
        
        if(isDuck) {
            System.out.println(input + " is a Duck number");
        } else {
            System.out.println(input + " is not a Duck number");
        }
        
        sc.close();
    }
}
Output :
Enter a number: 2030
2030 is a Duck number
Enter a number: 137
137 is not a Duck number
Explanation :

* We take user input as a string.

* We check if the first character of the string is '0' or not. If it is, then the number is not a Duck number. If it's not, we move on to the next step.

* We iterate through the string from the second character and check if there's any '0' present. If there is, then the number is a Duck number.

* If the number is a Duck number, we print a message accordingly. If it's not, we print a different message.