In: Computer Science
import java.util.Stack;
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Stack<Integer> new_stack =
new Stack<>();/* Start with the empty stack */
Scanner scan = new
Scanner(System.in);
int num;
for (int i=0; i<10; i++){//Read
values
num =
scan.nextInt();
new_stack.push(num);
}
int new_k = scan.nextInt();
System.out.println(""+smallerK(new_stack, new_k));
}
public static int smallerK(Stack s, int k) {
//TODO: Find the number of elements
in stack s that are smaller (in value) than k
//Example: if s=[50, 20, 30, 40,
10[ and k=25, the method should return: 2
}
}
Please find below the method implementation as per requirement with required comment in each line:
public static int smallerK(Stack s, int k) {
int smallerKValue=0;//set number of smaller elements to 0
Iterator stackValue = s.iterator(); ////use iterator to iterate through stack values
while(stackValue.hasNext()) {//repeat while stack is not empty
if((int) stackValue.next() <k) {//if value in stack is less than the passed value k
smallerKValue++;//increment the counter
}//end if
}//end while when all elements are iterated
return smallerKValue;//return the counted value
}//end methor smallerK
--------------------------------------------------------------------------------
Full Program is as below:
--------------------------------------------------------------------------------
import java.util.Stack;
import java.util.Iterator;
import java.util.Scanner;
class Main {
public static void main(String[] args)
{
Stack<Integer> new_stack = new Stack<>();/* Start with the empty stack */
Scanner scan = new Scanner(System.in);
int num;
for (int i=0; i<10; i++){//Read values
num = scan.nextInt();
new_stack.push(num);
}
int new_k = scan.nextInt();
System.out.println(""+smallerK(new_stack, new_k));
}
public static int smallerK(Stack s, int k) {
int smallerKValue=0;//set number of smaller elements to 0
Iterator stackValue = s.iterator(); ////use iterator to iterate through stack values
while(stackValue.hasNext()) {//repeat while stack is not empty
if((int) stackValue.next() <k) {//if value in stack is less than the passed value k
smallerKValue++;//increment the counter
}//end if
}//end while when all elements are iterated
return smallerKValue;//return the counted value
}//end method smallerK
}
--------------------------------------------------------------------------------
Screenshot is as below:
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Output is as below:
--------------------------------------------------------------------------------
Green texts are inputs, 10-100 are stack elements and 55 is k value. 5 is returned by smallerK method