Write a method which will take one number as an argument. (Feel free to use static method or instance method) Given a input number (integer) print the digits of the number. You must use while loop and modulus operator. This program must work for any positive integer. Negative integers are not cons idered as inputs.

Respuesta :

Answer:

// here is code in java.

import java.util.*;

// class definition

class Main

{

// method that return the digits of number

   public static void dig(int num)

   {

   // while loop

       while(num>0)

       {

           // print the digits

           System.out.println(num%10);

           num=num/10;

       }

   }

   //driver method

public static void main (String[] args) throws java.lang.Exception

{

   try{

    // scanner object to read input string

       Scanner s=new Scanner(System.in);

        // variable

       int num;

       System.out.print("please enter the number: ");

       //read the number

       num=s.nextInt();

       // validate the input, read a positive number only

       while(num<=0)

       {

           System.out.print("enter a positive number only:");

           num=s.nextInt();

       }

       System.out.println("digit of number are:");

       // call the function

      dig(num);

   }catch(Exception ex){

       return;}

}

}

Explanation:

Read a number from user and assign it to variable "num".Check if it is positive or not.If input is negative then ask user to again enter a positive number till user enter a positive number.Then call the function with input number. In this method it will find the digits of the number in the while loop using modulus "%" operator.

Output:

please enter the number: -345

enter a positive number only:1234

digit of number are:

4

3

2

1