11.6k views
3 votes
Write the definition of a method named countPos 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 in standard input and returns the number that are positive. So if the input were: 19 -5 -3 -251 14 -7 -14 6 the method would return 3 because there are 3 positive integers there. The method must not use a loop of any kind (for, while, do-while) to accomplish its job.

User Mazore
by
5.7k points

1 Answer

3 votes

Answer:

Here is the method countPos

static int countPos(Scanner input){ //method that takes a reference to a Scanner object

int counter=0; // to count the positive integers

int number; //to store each integer value

if(input.hasNextInt()){ //checks if next token in this scanner input is an integer value

number=input.nextInt(); //nextInt() method of a Scanner object reads in a string of digits and converts them into an int type and stores it into number variable

counter=countPos(input); //calls method by passing the Scanner object and stores it in counter variable

if(number>0) //if the value is a positive number

counter++; } //adds 1 to the counter variable each time a positive input value is enountered

else { //if value is not a positive integer

return counter; } //returns the value of counter

return counter; } //returns the total count of the positive numbers

Step-by-step explanation:

Here is the complete program:

import java.util.Scanner; //to take input from user

public class Main { //class name

//comments with each line of method below are given in Answer section

static int countPos(Scanner input){

int counter=0;

int number;

if(input.hasNextInt()){

number=input.nextInt();

counter=countPos(input);

if(number>0)

counter++; }

else {

return counter; }

return counter; }

public static void main(String[] args) { //start of main function

System.out.println("Number of positive integers: " + countPos(new Scanner(System.in))); } } //prints the number of positive integers by calling countPos method and passing Scanner object to it

The program uses hasNextInt method that returns the next token (next input value) and if condition checks using this method if the input value is an integer. nextInt() keeps scanning the next token of the input as an integer. If the input number is a positive number then the counter variable is incremented to 1 otherwise not. If the use enters anything other than an integer value then the program stops and returns the total number of positive integers input by the user. This technique is used in order to avoid using any loop. The program and its output is attached

Write the definition of a method named countPos that receives a reference to a Scanner-example-1
User Miushock
by
6.2k points