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

0 0
Add a comment Improve this question Transcribed image text
Answer #1

solution

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]

Add a comment
Know the answer?
Add Answer to:
How would one go about pushing the error literal :error: to a Stack in Java? I...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT