Variable can't be resolved to a field [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to update a enqueue function of a queue class so that it enqueue a stack item (nrm LIFO stack) according to its size.
But when I try to use the variable for the size of the stack (N) it says variable can't be resolved or it is not a field. All fields and methods are public in all classes.
public void add(SpecialStack SpecialStack) {
Node<SpecialStack> oldlast = last;
last = new Node<SpecialStack>();
last.astack = SpecialStack;
int a = last.astack.N;
last.next = null;
if (isEmpty())
first = last;
else
oldlast.next = last;
N++;
}
This is the function who is problematic, and the class which i want to add:
public class SpecialStack {
public Node <Integer> first;
public int N;
public static class Node <Integer> {
public Integer value;
public Node next;
Node (Integer a) {
value = a;
}
}
}

N exists inside SpecialStack, not inside WhateverClassDeclaresTheAddMethod, yet you try to do N++ inside WhateverClassDeclaresTheAddMethod. To fix the compile problem you would need to do last.astack.N++ instead, but that doesn't make sense because that's the size of the SpecialStack, not the size of the Queue.
You really need an N inside of Queue so you can increment that.
(Note: please don't name your variables and fields using something that starts with an upper case letter. That makes most of us cringe.)
As for the problem on int a= last.astack.N... you haven't declared last.astack to be of type SpecialStack. You've made it something else, something more general, that doesn't have an N. So even though the object stored in last.astack is a SpecialStack and has an N, the compiler can't tell because it can't see the instance at compile time.

Related

Access a linked list through a method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
In this method I'm suppose to remove all zeroes from a linkedlist but I'm not sure how to access the linked list. I am not allowed to change the parameters of the method but I can change the return. How can I access the linkedlist to modify it?
public domino removeZero() {
// ****** student exercise
return this;
}
This is the line that calls the method:
train = train.removeZero();
The name of the class is domino.
Here is the complete program http://pastebin.com/EwNJj9mV
You can use some getter setter method
like store your linkedlist in one different class's static variable and than in your method get that static variable's value.
import java.util.LinkedList;
public class linkedListStorage {
private static LinkedList linkedList;
public static LinkedList getLinkedList() {
return linkedList;
}
public static void setLinkedList(LinkedList linkedList) {
linkedListStorage.linkedList = linkedList;
}
}
now when you get your linkedlist put it via setter method
import java.util.LinkedList;
class JunitTest {
public static void main(String[] args) {
// set linked list to storage class's variable
linkedListStorage.setLinkedList(your linked list variable);
}
}
now use your linked list in your method
public domino removeZero() {
// ****** student exercise
// get your linked list from storage class
LinkedList ll = linkedListStorage.getLinkedList();
return this;
}
I suspect you need to learn some basics about object oriented programming and then re-ask the question. The method you have included in your question (removeZero) is a member of a class (domino) that has fields you can access inside the method. In other words removeZero has access to the linked list because it's a method of the linked list object.
In this case the code would be something like:
public domino removeZero() {
domino first = null;
for (domino current = this; current.next != null; current = current.next) {
if (current.spot1 == 0 || current.spot2 == 0) {
if (current.back != null)
current.back.next = current.next;
if (current.next != null)
current.next.back= current.back;
} else if (first == null) {
first = current;
}
}
return first;
}
By the way, you should tell your teacher to use capital letters to start class names. It should be called Domino, not domino.

Reversed stack returns one item

I have a generic LinkedStack class with a LinkedStack reversed method
It creates a new LinkedStack say newLinkedstack and pushes items from the current stack by popping them. So at the end of the operation the current stack is left empty and newLinkedStack contains the same items/elements that were in "this" stack only in reverse order.
My code compiles but when I create and fill up a stack and then print out the contents,
I only get one result.
public LinkedStack<T> rev()
{
LinkedStack<T> revStack=new LinkedStack<T>();
//final int SIZE=this.size();
while(!(this.empty)){//for(int i=0;i<SIZE;i++)
{
revStack.push(this.pop());
}
return revStack;
}
For example
LinkedStack<String> newLS = new LinkedStack<String>();
newLS.push("noid");
newLS.push("enilec");
newLS.push("River");
newLS.push("Healing");
newLS.push("Pain");
and newLS.rev() returns Pain instead of a reversed stack
UPDATE
Here's my pop method
public T pop()
{
T element=peek();
top=top.next;
return element;
}
I have two push methods this one moves every element from input stack to current stack leaving input stack from argument empty
public void push(LinkedStack<T> stack){
//int SZE = stack.size();
while(!(stack.empty())){//formally for(int i=0;i<SZE;i++){
this.push(stack.pop());}}
Here's my other push method
public void push(T element)
{
top=new Node<T>(item,top);
}
I'm not sure where LinkedStack came from, but it seems that the bug is being caused by that class's implementation.
You'll have to post more source code if you want more specific help.

Java: Implement stack with one queue, any problems?

So I tried to implement a stack with just one queue and it appears to work, but I'm not sure if there's something wrong with it since most of the solutions I've seen online use two queues. Can anyone tell if me if there are problems with my implementation?
public class MyStack<T> {
/**
* #param args
*/
private Queue<T> q = new LinkedList<T>();
public MyStack(){
}
public static void main(String[] args) {
// TODO Auto-generated method stub
MyStack<String> s = new MyStack<String>();
s.push("1");
s.push("2");
s.push("3");
s.push("4");
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
System.out.println(s.pop());
}
public void push(T s){
q.offer(s);
}
public T pop(){
int n = q.size();
for(int i = 0; i < n-1; i++){
q.offer(q.poll());
}
return q.poll();
}
}
Output:
4
3
2
1
null
Your solution is inefficient because you have to loop through the whole stack every time you pop something from it. (Effectively you have to traverse the whole linked list, before removing the element that was at the end.)
Edit: Java's linked list is doubly linked anyway, so this is entirely pointless.
You should use either a Stack or a Deque or even a LinkedList.
Implementing your own is just ... pointless. Unless of course (as #bas suggests) you are doing a course on data structures in which case you should go Commando and implement your own structure from scratch. Using another structure because it is nearly like the one you are trying to make is like using a hammer with screws.
If you really need to implement something yourself something like this should work:
public class Stack<T> {
private Entry top = null;
private class Entry {
final Entry up;
final T it;
public Entry(Entry up, T it) {
this.up = up;
this.it = it;
}
}
public void push ( T it ) {
top = new Entry(top, it);
}
public T pop () {
if ( top == null ) {
throw new EmptyStackException();
}
T it = top.it;
top = top.up;
return it;
}
}
NB: This may not be thread safe.
There is absolutely no reason a stack should use two queues. As a matter of fact, it only needs to keep track of one top-node that references the nodes below it.
The code seems to work, but as nachokk said, this is not the site for code review. This site is ment if you run into errors and require assistance.
You must use two queues ONLY when you have basic queues operations, like enqueue and dequeue. When you can use other methods, especially iterating over queue, you can do it with only one queue, like you did.

how do i make a stack out of a linked list? [duplicate]

This question already has answers here:
Closed 10 years ago.
I'm trying to create a Stack to take a string and add each of the strings characters to it, but I was told it would be far more efficient use a LinkedList. How would I use a LinkedList to create and manipulate a stack?
An example would be very appreciated!
Ok, the problem is that you're not using First at all. Try the following:
public class Example
{
private LinkedList aList = new LinkedList();
public void push(char c) {
aList.addFirst(c);
}
public Object pop() {
return aList.removeFirst();
}
public boolean empty() {
return aList.isEmpty();
}
public static void main(String[] args) {
Stack exmpStack = new Stack();
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
exmpStack.push(ranString.charAt(i));
}
while (!exmpStack.empty()) {
System.out.print(exmpStack.pop());
}
}
}
Because you never use First it's always null - so your loop never runs at all! Instead of using that at all, just use the build in isEmpty() function.
Edit: Of course, you don't really need those functions at all - the following will work fine:
public class Example
{
private LinkedList aList = new LinkedList();
public static void main(String[] args) {
String ranString = "Dad";
for (int i = 0; i < ranString.length(); i++) {
aList.push(ranString.charAt(i));
}
while (!aList.isEmpty()) {
System.out.print(aList.pop());
}
}
}
Now this is still a bit unsafe - you can go one step further by using the following:
private LinkedList<Character> aList = new LinkedList<>();
That way it's a bit safer, and returns Characters instead of Objects - and Characters can be implicitly cast to char :)
Java's LinkedList is a doubly linked list, with efficient accessors to get, add, and remove elements both at the end and at the head of the list, so you can use those methods to emulate a stack.
A LinkedList provides more operations that that of a stack.
You use a stack for pushing and popping your characters of your string. However you can only retrieve the character in the order that opposite the way you insert your string. So are you sure if you want this behaviour.
A linkedlist allows you to add/retrieve your data either from head / tail.
LinkedList is indeed more efficient, as Stack comes with synchronized methods by virtue of its reliance on Vector. In single-threaded applications, using the latter means paying the synchronization price for no benefit. Even in multi-threaded applications, you may want more control over synchronization.
Here's a possible LinkedList based solution. Please note the use of composition instead of inheritance. This will give you a well behaved Stack that cannot be abused by using List-related methods.
class MyStack<T> {
private List<T> list = new LinkedList<T>();
public void push(T object) { list.add(0, object); }
public T pop(T object) {
if (isEmpty()) throw new NoSuchElementException();
return list.remove(0);
}
public boolean isEmpty() { return list.isEmpty(); }
}
Nonetheless, if your stack is meant only for string characters as your question suggests, you might want to emulate a stack directly on a dynamic character array. I will leave that as an exercise to the reader, or I may provide it in a future edit.
Here is the sample: Stack implementation. Hope it helps.
It is done with C# but you get the idea

Return the stack element at a given index without modifying the original Stack in Java

Ok I was recently asked this in an interview, and I am intrigued. Basically I have a stack with a certain set of values, I want to pass the stack object in a function and return the value at certain index. The catch here is that after the function is complete, I need the stack unmodified; which is tricky because Java passes reference by value for objects. I am curious if there is purely a java way to do using push(), pop(), peek(), isempty() and primitive data type. I am against copying the elements into an array or string. Currently the cleanest I have got is using clone, find the code below:
import java.util.Stack;
public class helloWorld {
public int getStackElement( Stack<Integer> stack, int index ){
int foundValue=null;//save the value that needs to be returned
int position=0; //counter to match the index
Stack<Integer> altStack = (Stack<Integer>) stack.clone();//the clone of the original stack
while(position<index)
{
System.out.println(altStack.pop());
position++;
}
foundValue=altStack.peek();
return foundValue;
}
public static void main(String args[]){
Stack<Integer> stack = new Stack<Integer>();
stack.push(10);
stack.push(20);
stack.push(30);
stack.push(40);
stack.push(50);
stack.push(60);
helloWorld obj= new helloWorld();
System.out.println("value is-"+obj.getStackElement(stack,4));
System.out.println("stack is "+stack);
}
}
I understand that cloning is also copying, but that's the basic flaw I am aiming to remove. Stripped down I am asking if I would be actually be able to pass the stack's value instead of passing the value of its reference.
Thanks in advance.
int position =5;
Integer result = stack.get(position);
Java Doc here
If you cannot use another stack, you can cheat and abuse a local variable on the call stack for the same purpose by making a recursive method:
public static <T> T getStackElement(Stack<T> stack, int index) {
if (index == 0) {
return stack.peek();
}
T x = stack.pop();
try {
return getStackElement(stack, index - 1);
} finally {
stack.push(x);
}
}

Categories

Resources