Advertisement
farhansadaf

Problem 1

Jul 20th, 2020
1,232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.52 KB | None | 0 0
  1. import java.util.Scanner;
  2. import java.util.Stack;
  3.  
  4. /**
  5.  * PROBLEM *
  6. Write a program to insert 5 float values in a dynamic list.
  7. Now take user input for a variable named “option”.
  8. If the option is 1 then insert another value.
  9. If option is 2 delete the top value from the list.
  10. If the option is 3 just output the top value.
  11. Apply stack list to implement the above-mentioned solution and use proper stack methods.
  12. **/
  13.  
  14. public class Problem1 {
  15.  
  16.     public static void main(String[] args) {
  17.         Scanner scanner = new Scanner(System.in);
  18.         Stack<Float> stack = new Stack<Float>();
  19.        
  20.         // Inserting 5 values in a dynamic list (Stack)
  21.         System.out.print("Enter 5 float values: ");
  22.         for (int i = 0; i < 5; i++) {
  23.             stack.push(scanner.nextFloat());
  24.         }
  25.        
  26.         System.out.println("Dynamic list: " + stack + "\n\n");
  27.        
  28.         // Taking user input in varriable "option"
  29.         System.out.print("Enter your option (1/2/3): ");
  30.         int option = scanner.nextInt();
  31.        
  32.         switch (option) {
  33.             case 1:
  34.                 System.out.print("User option is 1. So enter a value to insert into the list:  ");
  35.                 stack.push(scanner.nextFloat());
  36.                 System.out.println("\n" +"Dynamic list: " + stack + "\n\n");
  37.                 break;
  38.             case 2:
  39.                 System.out.println("User option is 2. So deleting top value from the list...  ");
  40.                 stack.pop();
  41.                 System.out.println("\n" + "Dynamic list: " + stack + "\n\n");
  42.                 break;
  43.             case 3:
  44.                 System.out.print("User option is 2. So top value is : " + stack.peek());
  45.                 break;
  46.         }
  47.        
  48.        
  49.         scanner.close();
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement