In this project, we are going to check whether the user entered number is a Duck number or not in Java language. We will learn what is a Duck number, what functions and methods we have used.
In this tutorial, we will study whether the given number is a Duck number or not in Java.
Duck number: A Duck number is a positive integer number that contains zeroes in it.
For example, 1024 is considered a Duck number but 0124 is not. Number leading or initiating with zero is not considered as a Duck number. Even 00124 is not a duck number.
What logic are we using to check on duck numbers? Firstly, we will take input from the user. Then call a static boolean function to check it.
Once we call the static boolean function, we measure the string's length and use a special method - charAt( )
The charAt() is a method that returns the character at a specified number in the string.
Example:
Return the first character of charAt( )-
public class printstring { public static void main(String[] args) { String Str = "Hello World"; char op = Str.charAt(0); System.out.println(op); } }
The output of this function:
H
Now, In this code, we have used two while loops:
1) First, While loop to check the initial digits.
2) Second, While loop to check the remaining digits of the given number.
Our second while loop decides whether the given number is a duck number or not. As when "number.charAt(x) == z" will be satisfied in the If-else conditional statement then the boolean statement(true/false) is returned and based on that main driver method if-else is operated.
Note: Here, we have defined number in the string because charAt( ) only works on the string.
import java.util.Scanner; // Check whether the given number is duck number or not in Java. // Main class named Ducknumber. public class Ducknumber{ // Function to check the given number is duck number or not. static boolean checkducknumber(String number) { int x = 0; int l; l = number.length(); int z='0'; while (x < l && number.charAt(x) == z) //The charAt() is a method which returns the character at a specified number in the string. { x++; // Ignore the initial zeroes(0's). } while (x < l) { if (number.charAt(x) == z) // Check the remaining digits in the number. { return (true); } x++; } return(false); } // Driver Method of this code. public static void main(String args[]) { Scanner scan = new Scanner(System.in); System.out.println("Enter the number:"); String number = scan.nextLine(); if (checkducknumber(number)) { System.out.println("The given number is a duck number"); } else { System.out.println("The given number is not a duck number"); } } }
Submitted by Vedanti Ravish Deshmukh (vedantid30)
Download packets of source code on Coders Packet
Comments