KnowledgeBoat Logo

Computer Applications

Create a program in Java to find out if a number entered by the user is a Duck Number.

A Duck Number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. For example, 6710, 8066, 5660303 are all duck numbers whereas 05257, 080009 are not.

Java

Java Conditional Stmts

12 Likes

Answer

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class KboatDuckNumber
{
    public void duckNumberCheck() throws IOException {
        
        InputStreamReader reader = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(reader);
        System.out.print("Enter number: ");
        boolean isDuck = false;
        boolean firstZero = false;
        int c = 0, d; 
        
        /*
         * 10 is the ASCII code of newline
         * We will read from inputstream
         * one character at a time till we
         * encounter a newline i.e. enter
         */
        while((d = in.read()) != 10) {
            
            char ch = (char)d;
            
            if (c == 0 && ch == '0'  ) 
                firstZero = true;
            
            if (!firstZero && ch == '0')
                isDuck = true;
                
            c++;
        }
        
        if (isDuck)
            System.out.println("Duck Number");
        else
            System.out.println("Not a Duck Number");
    }
}

Output

BlueJ output of Create a program in Java to find out if a number entered by the user is a Duck Number. A Duck Number is a number which has zeroes present in it, but there should be no zero present in the beginning of the number. For example, 6710, 8066, 5660303 are all duck numbers whereas 05257, 080009 are not.

Answered By

7 Likes


Related Questions