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
}
}
The required method is highlighted as bold in the below source code:
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<5; 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 <Integer> s, int
k)
{
//variable declaration and initialization
int count=0;
//count the values less than k
while(!s.empty())
{
int x = s.pop();
if(x<k)
count++;
}
//return statement
return count;
}
}
OUTPUT:
50 20 30 40 10
25
2
Get Answers For Free
Most questions answered within 1 hours.