好吧,我正在學java的暑期課程。是的,這是課堂上的任務,但我很難過,已經休息了一下,仍然無法理解邏輯錯誤是什麼。我將使用鏈接列表進行堆疊。外部和內部類應該在UserStack中實現。 UserStack實現由教師提供的MyStack。 StackApp的主要內容。它編譯並運行。它正確地要求輸入一個整數。將刪除,如果有東西要刪除,並會嘗試偷看,如果有東西要顯示。但它總是說它已刪除或正在顯示數字0.我是否需要嘗試執行toString重寫?我問我的教授,他告訴我像其他學生一樣去谷歌。Java Stack peek方法顯示0而不是正確的數字
MyStack.java
public interface MyStack
{
public void push (int item);
public int pop();
public int peek();
public boolean isEmpty();
}
UserStack.java
import java.util.NoSuchElementException;
public class UserStack implements MyStack
{
private class Node
{
public int value;
public Node link;
public Node(int data)
{
data = value;
}
}
private Node head = null;
public void push (int item)
{
Node newHead = new Node(item);
newHead.link = head;
head = newHead;
}
public int pop()
{
if(isEmpty())
throw new NoSuchElementException();
int tmp = head.value;
head = head.link;
return tmp;
}
public int peek()
{
if(isEmpty())
throw new NoSuchElementException();
int tmp = head.value;
return tmp;
}
public boolean isEmpty()
{
return head == null;
}
}
StackApp.java
import java.util.Scanner;
class StackApp
{
UserStack stack = new UserStack();
public void displayMenu()
{
System.out.println ("1) Add an integer to the list\n" +
"2) Remove last integer entered\n" +
"3) Look at last integer entered\n" +
"0) Exit the program");
System.out.print ("Selection: ");
}
public StackApp()
{
int option;
Scanner input = new Scanner(System.in);
do{
displayMenu();
option = input.nextInt();
switch (option)
{
case 1:
int number;
System.out.println("Enter integer to add: ");
number = input.nextInt();
stack.push(number);
break;
case 2:
int number2 = stack.pop();
System.out.println("Interger removed: " + number2);
break;
case 3:
int number3 = stack.peek();
System.out.println("Next Interger: " + number3);
break;
case 0:
System.out.println("Goodbye");
break;
default:
System.err.println("Unrecongized choice");
break;
}
}while(option != 0);
}
public static void main(String[] args)
{
new StackApp();
}
}
Typo in your' Node'構造函數:'data = value;'應該是'value = data;'。 –
非常感謝。自從週一以來我一直在盯着這個,從來沒有注意到這一點。 – GenCrash10