In: Computer Science
ENHANCE this part by allowing the user to enter as many scores as they want, until they enter -1 to stop.
push 2
push 3
push 1
pop
pop
push 5
push 4
pop
push 6
push 9
push 7
pop
push 1
pop
pop
Note that because we are typing information so use left side line to be the bottom of your stack
|
Show what is written by the following segment of code (i.e.
output on the screen), given that item1, item2, and item3 are
int variables, and stack is an object that fits our
abstract description of a stack.
(Assume that you can store and retrieve variables of type
int on stack.)
int item1 = 4;
int item2 = 2;
int item3 = -3;
stack.push(item2);
stack.push(item1);
stack.push(item1 + item3);
item2 = stack.peek();
stack.push (item3 - item3);
stack.push(item2);
item1 = stack.peek();
stack.push(item1 + item3);
stack.push(3);
item1 = stack.pop();
System.out.println(item1 + " " + item2 + " " + item3);
while (!stack.empty())
{
item1 = stack.pop();
System.out.println(item1);
}
|
Answer for part 1
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[])
{
Stack<String> myStacks = new Stack<String>();
Scanner sc = new Scanner(System.in);
for(int i=0;i<2;i++){
System.out.print("Enter Name:");
String name = sc.nextLine();
myStacks.push(name);
}
System.out.println("\nThe names and their lengths are: ");
while(!myStacks.empty()){
String name = myStacks.pop().toString();
System.out.println("Name:"+name+ " Length:"+name.length());
}
}
}
Answer for part 2
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[])
{
Stack<Integer> myScores = new Stack<Integer>();
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter 5 integers: ");
for(int i=0;i<5;i++){
System.out.print("Enter integer:");
int num = sc.nextInt();
myScores.push(num);
}
System.out.println("\nThe scores are: ");
int sum = 0;
while(!myScores.empty()){
int thisscore = myScores.pop();
System.out.print(thisscore+"\t");
sum = sum + thisscore;
}
System.out.println("\nSum of all:"+sum);
System.out.println("Average:"+(sum/5));
}
}
If you have any doubt get back through comments