In this tutorial you will learn about the Program to check Duck Number In Java and its application with practical example.
In this tutorial, we will learn to create a Java Program to check Duck Numbers in Java using Java programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following Java programming topics:
- Java Operators.
- Basic Input and Output function in Java.
- Class and Object in Java.
- Basic Java programming.
- If-else statements in Java.
- For loop in Java.
What is a Duck Number?
Duck number is a special positive number that contains zero in within the number except starting are called a Duck number.
Example:
1202
Program to check Duck Number In Java
In this program we will find given number is a Evil number or not in using java programming.We would first declared and initialized the required variables. Next, we would prompt user to input the a number.Later we find number is Evil number or not let’s have a look at the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
// Java program to find number is Duck number or not... import java.util.Scanner; public class Duck { public static void main(String args[]) { // Declaring variables and taking value from user.. Scanner sc = new Scanner(System.in); System.out.print("Input any number : "); String numToString = sc.nextLine(); int l = numToString.length(); int c = 0; // initiating counter to zero char ch; // finding number of zeros in a number for(int i=1;i<l;i++) { ch = numToString.charAt(i); if(ch=='0') c++; } char f = numToString.charAt(0); // checking condition zero at first position if(c>0 && f!='0') System.out.println("Duck number"); else System.out.println("Not a duck number"); } } |
Output
Duck number
Not a Duck Number.
In the above program, we have first declared and initialized a set variables required in the program.
- numToString = it will hold entered number.
- l= it will hold length of a string.
- ch= it will charters of a string.
- c= it will count zeros in numbers.
After declaring variables in the next statement user will be prompted to enter a value and which will be assigned to variable ‘number’.
Here we will convert given number into string as shown in picture above after that we declare c,ch and l variables to hold value temporary l for length , c for number of zeros in number and ch for holding character of a string
after that with the help of while loop we search number of zeros in a string if zeros are present in string increase the counter value of c to one(c++).
and finally we will check if if statement that the value of c is grater than zero and zero is not present at first location
if both condition satisfied then the number is Duck number and if not then it not a duck number.