Write the definition of a method named add that receives a reference to a Scanner object associated with a stream of input consisting of integers only. The method reads all the integers remaining to be read from the stream and returns their sum. So if the input were 3 51 204 17 1040 the returned value would be 1315

The method must not use a loop of any kind (for, while, do-while) to accomplish its job.

Respuesta :

Answer:

import java.util.*;

class Main  

{

   public static void main(String[] args)

   {

       System.out.println("Enter integers and 0 to exit");

       Scanner a1=new Scanner(System.in);

       System.out.println(add(a1));

       

   }

  public static int add(Scanner a1)

  {

        int total = a1.nextInt();

          if (a1.hasNextInt())

              {

                 total =total +add(a1);

              }

       return total;

   }

}

Explanation:

The only thing that needs explanation here is hasnextInt. This returns true if entered number is integer and false if entered is not an integer. And rest is as shown in the program.

ACCESS MORE