Duck Number in Java
Check a duck number in Java by reading text, validating digits, and scanning for a later zero. Leading zeros stay visible and disqualify the input.
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 if (!s.matches("[0-9]+")) {10 System.out.println("Enter digits only");11 sc.close();12 return;13 }1415 boolean isDuck = false;16 for (int i = 1; i < s.length(); i++) {17 if (s.charAt(i) == '0') {18 isDuck = true;19 break;20 }21 }2223 if (isDuck && s.charAt(0) != '0') {24 System.out.println(s + " is a Duck Number");25 } else {26 System.out.println(s + " is not a Duck Number");27 }28 sc.close();29 }30}
Sample Output
Enter a number: 1023 1023 is a Duck Number
The search sees 0 at position 1 of 1023, sets isDuck to true, and stops. The first character 1 passes the final check.
In this one
- Preserve leading zeros with text input
- Search from the second character
- Validate digits before indexing
How it works
- 1
Read the input line as s.
- 2
Reject empty or non-digit input.
- 3
Search positions 1 through length - 1 for 0.
- 4
Require a non-zero first digit before accepting.
Edge cases
Leading zero
Enter 0120
It has a later zero but starts with zero, so it is not a duck number.
Empty or signed input
Enter an empty line or -102
The digit-only check reports invalid input without reading an absent first character.
What's going on
A duck number is a positive whole number whose written digits include a zero after the first digit, without starting with zero. For example, 1023 qualifies but 0123 does not. This task reads text so leading zeros remain visible for the check.
Scanner is the keyboard reader, and nextLine reads the complete input line into s. A string is a text value. The code first checks that every character is a digit from 0 to 9. It then searches positions from 1 onwards for a zero, deliberately skipping the first position.
A boolean is a true-or-false value; isDuck records whether a later zero was found. The final condition also checks the first character is not zero. Do not read this as an int first, because that would discard leading zeros. Empty input, signs, spaces, and words are rejected before any character position is accessed.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which input is a duck number?
Pick an answer to check it.
Question 2
What position is the first character?
Pick an answer to check it.
Questions people ask
Why start the loop at 1?
Position 0 is the leading digit, which is checked separately.
Does the number 0 qualify?
No. It starts with zero and has no later digit.
Why use a string instead of int?
A string keeps exactly the typed digits, including any leading zeros.