【发布时间】:2022-01-10 23:38:01
【问题描述】:
我的 adt 类中的 return stack.get(stack.size-1).getBookName() 不起作用。这行代码在 pop 中。每当我运行它并想从堆栈的最顶部删除某些内容时,它会删除正确的内容,但不会返回删除的正确书籍。是错误的 .getBookName() 部分吗?请帮忙!
//main class
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scan=new Scanner (System.in);
Scanner scanString= new Scanner(System.in);
int menuInput=0;
String bookName;
int pages;
String author;
ADT stack=new ADT ();
while(menuInput!=6)
{//menu
System.out.println("1. Add an book to the stack");
System.out.println("2. Remove an book from the stack");
System.out.println("3. Return the top book");
System.out.println("4. Return the length of the stack");
System.out.println("5. Return if the list is empty");
System.out.println("6. Exit");
menuInput=scan.nextInt();
if (menuInput==1)
{
System.out.println("What book do you want to add?");
bookName=scanString.nextLine();
System.out.println("How many pages are in the book?");
pages=scan.nextInt();
System.out.println("Who is the author of the book?");
author=scanString.nextLine();
stack.push(bookName, pages, author);
}
if (menuInput==2)
{
System.out.println(stack.pop());
}
if (menuInput==3)
{
System.out.println(stack.peek());
}
if (menuInput==4)
{
System.out.println(stack.length());
}
if (menuInput==5)
{
System.out.println(stack.isEmpty());
}
}
}
}
//adt class
import java.util.*;
public class ADT { //ADT stands for Abstract Data Type
String piece;
ArrayList <Book> stack = new ArrayList<Book>();
public ADT(){
ArrayList <Book> stack = new ArrayList<Book>();
}
public ADT(Book b){
ArrayList <Book> stack = new ArrayList<Book>();
stack.add(b);
}
public void push(String bN,int pg, String aut)
{
Book one=new Book(bN,pg,aut);
stack.add(one);
}
public String pop()
{
stack.remove(stack.size()-1);
return "Book removed: " + stack.get(stack.size()-1).getBookName();
}
public String peek()
{
return "First book of the stack: " + stack.get(stack.size()-1).getBookName();
}
public int length()
{
return stack.size();
}
public boolean isEmpty()
{
if (stack.size()==0)
return true;
else
return false;
}
}
//book class
public class Book{
private String bookName;
//name of the book
private int pages;
//pages in the book
private String author;
//author of the book
public Book(String bN,int pg, String aut)//bN=book name, pg=pages, aut=author
{
bookName=bN;
pages=pg;
author=aut;
}
public String getBookName()
{
return bookName;
}
}
【问题讨论】: