Duck Number in Java
Check whether a number is a duck number (contains zero, but not at the first position).
IntermediateModule 3: Loop ProgramsExample 25 of 25
duck-number.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a number: ");7 String s = sc.nextLine();89 boolean isDuck = false;10 for (int i = 1; i < s.length(); i++) {11 if (s.charAt(i) == '0') {12 isDuck = true;13 break;14 }15 }1617 if (isDuck && s.charAt(0) != '0') {18 System.out.println(s + " is a Duck Number");19 } else {20 System.out.println(s + " is not a Duck Number");21 }22 sc.close();23 }24}
Output
Enter a number: 1023 1023 is a Duck Number
What's going on
We work with the string form, ensuring the first digit is not zero and some later digit is zero.