Populating stack causes error - java

I'm populating a stack instance variable with elements of the array el, but in the line below it's giving me an error although I specified that it's a stack of Integers.
Error:
Incompatible types - found java.util.Stack but expected java.lang.Integer...
Code:
import java.util.Stack;
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
el[i] = stack; /** THIS LINE*/
}
}
}

To add an item to the top of the stack, use the push method.
Example:
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i]);
}
}
This will push elements from the el array into the stack.

I think you want to add elements of el into stack . You were trying to assign stack object to el[i] which is not possible. Its obvious that you got error.
So your code should be like following :
public class SortedStack
{
private Stack<Integer> stack = new Stack<Integer>();
public SortedStack(Integer[] el)
{
for(int i = 0; i < el.length; i++)
{
stack.push(el[i];
}
}
}

I'm not a Java developer but I'm guessing if you want to put a value on the stack you'll need something like:
stack.push(el[i]);
The reason for your error is your trying to assign the i-th Element in an Integer array, to be a Stack. This is failing because it can't cast a Stack to an integer.

Use Stack.push() method.
stack.push(el[i]);

To use a stack, you want to push() your item on top of it, and pop() it from the stack when you're ready to use it again. In your case, it seems more appropriate to inherit the stack, than to wrap it.
import java.util.Stack;
public class SortedStack extends Stack<Integer>
{
public SortedStack(Integer[] el) // Why "Sorted"? You're not sorting here...
{
for(int i = 0; i < el.length; i++)
{
this.push(el[i]); /** THE ERROR IS THIS LINE */
}
}
}
Doing this, you can use your SortedStack just like any regular stack, with the addition of adding a whole range of elements in the constructor. You might also want to implement a PushRange() method, that can be called after the object is instantiated.

Related

How to remove elements from an ArrayList?

ArrayList<Rolling> copy = new ArrayList<Rolling>();
for (int i = 0; i < sequence.size(); i++) {
copy.add(sequence.get(i));
}
ListIterator<Rolling> listIterator = copy.listIterator();
// Remove each element one by one
for (int j = 0; j < copy.size(); j++) {
listIterator.next();
if (copy.contains()) {
listIterator.remove();
}
}
public static void main(String[] args) {
remove(sequenceOfDice(4), 4);
}
}
short summary: I have a class called Rolling and I wanna thru this method copy its elements and then remove the value of n from the new list and return the rest but I am not geting far since i got a couple of errors.
The error I get is:The method contains(Object) in the type ArrayList is not applicable for the arguments ()
the method "copy.contains()" should have a parameter(argument).
that means,you should write like this "copy.contains(x)"
what's more, i think you are a new learner.because your code have many errors or sames strange.
your comment is "// Remove each element one by one"
but you said "then remove the value of n from the new list", is this conflict?
please paste all the code and compile it successfully on your laptop.
By the way, in a for loop, we usually use iterator to remove element because remove element will cause modcount change,try below code:
while(listIterator.hasNext()){
Rolling next = listIterator.next();
if (copy.contains(next)) {
listIterator.remove();
}
}

Duplicating elements in a stack?

So I have a method to take a stack of Integers, and return the stack with all of the elements duplicated, and in the same order. My problem is with the method i currently have, Im getting an infinite loop problem on all cases except when the Stack is empty. What can i do to complete the duplication without a looping problem?
public void stutter(Stack<Integer> Integ)
{
Integer first;
for(int i = 0; i < Integ.size(); i++)
{
first = Integ.pop();
Integ.push(first);
Integ.push(first);
}
}
Each time you push another integer, you increase the original size of your stack, pushing your "i" limit forward.
You should return a new Stack, preferably using (pre java8):
public Stack<Integer> stutter(Stack<Integer> from) {
Stack<Integer> stk = new Stack<>();
for(Integer i: from) {
stk.push(i);
stk.push(i);
}
return stk;
}
ofc, its an inifinite loop. You increase the Integ.size() inside of the loop by Integ.push().
Try something like that. Save the size inside a var befor starting to push new elements into it.
int size = Integ.size();
for(int i = 0; i < size; i++){
first = Integ.pop();
Integ.push(first);
Integ.push(first);
}
Just create new stack with duplicates (and replace old if needed).

My get method will not display arraylist value

I am new to java and stackOverflow so please be patient if I don't post all the necessary information about my question. Basically, I am trying to read lines from a .txt file and store them in a Stack. I also need to access this Stack in a different class. So I created a get method but it always returns null. Please help!
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.Stack;
public class Hints {
private Stack stack;
private File f;
private String line;
private Scanner scanner;
public Hints(){
f = new File("hints.txt");
stack = new Stack();
}
public void getList() throws FileNotFoundException, IOException {
scanner = new Scanner(f);
while(scanner.hasNextLine()) {
line = scanner.nextLine();
stack.add(line);
}
scanner.close();
}
public Stack getStack(){
return stack;
}
}
When I try to print the stack with a simple System.out.print, it will come out as null. Where is my issue(s)?
Thank you.
Your code works fine. I think you are not calling the getList() method before you call the getStack() method.
try {
Hints hints = new Hints();
hints.getList(); // adds to the stack
Stack s = hints.getStack(); // return the stack
int stackSize = s.size();
for (int i = 0; i < stackSize; i++) {
System.out.println(s.pop()); // pop from the stack
}
} catch (IOException ex) {
Logger.getLogger(JavaApplication18.class.getName()).log(Level.SEVERE, null, ex);
}
You must call the getList() method first before you call the getStack() method. Because getList() method adds values that are read from the txt file. Then only you can call the getStack() method. Otherwise you don't have any values in the stack.
The code you presented looks fine so far. You initialize your stack by iterating through your textfile. So if the textfile contains lines, the stack will be filled with the data. So you might probably have a problem while printing your result.
Since java.util.Stack is derived from Vector, you can use the get(int) Method to access the data inside your stack. Therefore, you simply need a printing method that accesses the stack like this:
Hints h = new Hints();
h.getList();
Stack theStack = h.getStack();
for (int i = 0; i < theStack.size(); i++) {
System.out.println(theStack.get(i));
}
Now your stack should be printed correctly to the console.
And remember calling the getList() method before trying to access your stack. You should consider initializing the stack within the constructor. Maybe this is the thing you are missing.
This is my hint
public Hints() throws FileNotFoundException, IOException{
f = new File("hints.txt");
stack = new Stack();
getList(); // call get list in constructor.
}
When you create the hint its populate the stack.

How to print a stack in Java

I wrote a method that receives a queue as a parameter and then convert this queue into a stack. Now I want to try to print this method in the main to see if it works, but there isn't any toString method for stacks.
I already did some research and tried to convert stacks into arrays, but I can't get it to work. Printing the stack values in Java
How can I do this?
public static void QueueStack(Queue<Integer> q){
Stack<Integer> stack1 = new Stack<Integer>();
while(!q.isEmpty()){
int temp = q.dequeue();
stack1.push(temp);
}
Arrays.toString(stack1.toArray());
}
Did you try using the Stack classes' toString() method?
e.g.
stack1.toString();
Or was there a specific format you want to print out?
You could try the get(int index) method of the Vector class which Stack extends, assuming you don't want to pop the elements from your stack while you print them.
if (!tack1.isEmpty()) {
for(Object a : stack1) {
System.out.println(a);
}
}
Here, is a method to convert a given Queue to Stack:
public static void QueueStack(Queue<Integer> queue){
Stack<Integer> stack = new Stack<>();
for(Integer in: queue){
stack.push(in);
}
//Here, the output would be same as you inserted elements.As stack uses iterator which prints elements as they are inserted(a bug in stack iteration)
System.out.println("Stack: "+stack);
//You can use java 8 for-each style as well.
stack.forEach(System.out::println);
//If you want to traverse stack in LIFO manner..
while(stack.isEmpty){
System.ou.println(stack.pop());
}
//For better performance ArrayDeque<>() is preferred!
Deque<Integer> stack = new ArrayDeque<Integer>();
}
You could also do it very similar to how to initialized it.
while(!stack1.isEmpty())
{
int t = stack1.pop();
System.out.println(t);
}

Stack Trace Logger

I need to write a parent Java class that classes using recursion can extend. The parent class will be be able to realize whenever the call stack changes ( you enter a method, temporarily leave it to go to another method call, or you are are finsihed with the method ) and then print it out. I want it to print on the console, but clear the console as well every time so it shows the stack horizantaly so you can see the height of each stack to see what popped off and what popped on... Also print out if a baseline was reached for recursive functions.
First. How can I using the StackTraceElements and Thread classes to detect automatically whenever the stack has popped or pushed an element on without calling it manually?
Second, how would I do the clearing thing?
For instance , if I had the code:
public class recursion(int i)
{
private static void recursion(int i)
{
if(i < 10)
System.out.println('A');
else
{
recursion(i / 10 );
System.out.println('B');
}
}
public static void main(String[] argv)
{
recursion(102);
}
}
It would need to print out the stack when entering main(), when entering recursion(102) from main(), when it enters recursion(102 / 10), which is recursion(10), from recursion(102), when it enters recursion(10 / 10), which is recursion(1) from recursion(10). Print out a message out when it reaches the baseline recursion(1).. then print out the stacks of reversed revisitation of function recursion(10), recursion(102) and main(). finally print out we are exiting main().
Thread class allows managing OS threads, it does not have anything to do with the call-stack. StackTraceElement represents a stack-frame but you need a StackTrace to get to it.
You are looking for a notification for when the stack-trace changes, for example a frame is added (a method is entered) or removed (a method is exited).
By far the most appropriate tool for this task is AspectJ. It lets you define advices (a kind of method) that gets called (besides other cases) when other methods are entered or existed. These triggers that result in the advices getting called are called pointcuts -- they can be method entry, exit and the methods can be described using wildcards: the pointcut MyClass.get* applies to all get methods of MyClass.
I started to write my own before seeing your answer. It is simplistic in form but the shell is:
package stackTraceLogger;
import java.util.ArrayList;
public class StackTraceLogger
{
static final int MAX_ROW = Integer.MAX_VALUE;
static final int MAX_COLUMN = Integer.MAX_VALUE;
static public ArrayList<ArrayList<String>> stringTrace;
//private ArrayList<ArrayList<StackTraceElement>> stack;
public StackTraceLogger()
{
stringTrace = new ArrayList< ArrayList <String>>();
//stack = new ArrayList<ArrayList<StackTraceElement>>();
}
static public void addStack(StackTraceElement[] inputTrace)
{
int size = inputTrace.length;
// make an ArrayList with the strings of all the StrackTraceElements
ArrayList<String> str = new ArrayList<>(size);
for(int i = 0; i < size; i++)
{
str.add(i,inputTrace[i].getMethodName());
}
// Add the ArrayList to the 2D ArrayList of the stacks
}
static public void printTrace()
{
/* if(stringTrace.get(0).size() > 0)
{
for(int i = 0; i < stringTrace.size(); i++)
{
System.out.println(stringTrace.get(i));
for(int j = 0; j < stringTrace.get(j).size(); j++)
System.out.println(stringTrace.get(i).get(j));
}
}*/
}
static private ArrayList<String> convertToArrayList(StackTraceElement[] inputTrace)
{
ArrayList<String> strTrace = new ArrayList<>();
for(int j = 0; j < inputTrace.length; j++ )
strTrace.add(inputTrace[j].getMethodName());
return strTrace;
}
}

Categories