201k views
5 votes
In python please!!! Write the definition of a function named countPos that reads integer values from standard input until there are none left and returns the number that are positive. The function must not use a loop of any kind.

User Gober
by
4.2k 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

Step-by-step explanation:

User Banzay
by
4.3k points