Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How would one go about pushing the error literal :error: to a Stack in Java? I c

ID: 3707970 • Letter: H

Question

How would one go about pushing the error literal :error: to a Stack in Java? I can't just push the String ":error:", as that is different. Can someone give me an example of as simple as possible a way to push the error literal :error: onto a stack? Thanks.

3.1.1 Pushing Integers to the Stack push num where num is an integer possibly with a'-'suggesting a negative value. Here, -0' should be regarded as '0. Entering this expression will simply push num onto the stack. For example, input stack pu If num is not an integer, only push the error literal (error:) onto the stack instead of pushing num. For example, input stack prnshrror: push 2.5 error: push -x5

Explanation / Answer

import java.util.Arrays;

import java.util.InputMismatchException;

import java.util.Scanner;

import java.util.Stack;

public class ErrorStack {

public static void main(String[] args) {

Stack stack = new Stack<Object>();

Scanner scanner = new Scanner(System.in);

System.out.println("enter how many you want to push in the stack");

int no = scanner.nextInt();

for (int i = 0; i < no; i++) {

System.out.println("enter the input");

String input = "";

try {

input = scanner.next();

try{

Integer a=Integer.valueOf((String) input);

if(a instanceof Integer)

stack.add(input);

else

stack.add("error");

}catch(InputMismatchException e)

{

stack.add("error");

}

  

} catch (Exception e) {

stack.add("error");

}

}

System.out.println(Arrays.toString(stack.toArray()));

}

}

output

enter how many you want to push in the stack
3
enter the input
2.5
enter the input
2
enter the input
1
[error, 2, 1]

enter how many you want to push in the stack
3
enter the input
1
enter the input
2
enter the input
df
the stack values are[1, 2, error]

enter how many you want to push in the stack
3
enter the input
sdgd
enter the input
1
enter the input
dfg
the stack values are[error, 1, error]

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote