【问题标题】:I'm having trouble with arraylists, i don't get it to return the right words我在使用数组列表时遇到问题,我无法让它返回正确的单词
【发布时间】:2015-01-26 19:41:59
【问题描述】:

程序运行良好,但是当我试图让它返回“单词”时,它返回了适量的输出,但都有最后输入的名称。

例如。如果我在 ArrayList 中存储 3 个不同的书名,它会返回上一本书的 3 倍的名称。

有什么明显的错误吗?

(超类和其他类应该可以正常工作)

import java.util.*;

public class libraryManager {

public static void main (String [] args) {

  String input =" ";


  ArrayList<Book> books = new ArrayList<Book>();
  ArrayList<CD> cds = new ArrayList<CD>();

  Book booka = new Book();
  CD cda = new CD();

    System.out.println("Welcome to library management system");
    Scanner reader = new Scanner(System.in);

    Scanner newBook = new Scanner(System.in);


    do{           

        System.out.println("Main menu: ");
        System.out.println(" 1. Add book to the library ");
        System.out.println(" 2. Add CD to the library ");
        System.out.println(" 3. Print items ");
        System.out.println(" 4. Exit ");
        input = reader.nextLine();


         if (input.equals("1")){
             System.out.println("Input new book: ");
             input = reader.nextLine();
             booka.setName(input);
             books.add(booka); input ="1";
        }

        if (input.equals("2")){
            System.out.println("Input new CD: ");
            input = reader.nextLine();
            cda.setName(input);
            cds.add(cda);
        }

        if (input.equals("3")){
            System.out.println("Library contains:");
            for (int i= 0; i<books.size(); i++){
                System.out.println("Book: " + books.get(i).getName());
            }
            for (int i = 0; i<cds.size(); i++){
                System.out.println("CD: " +cds.get(i).getName());
            }

            break;
        }

  }while(!input.equals( "4"));
}
}

【问题讨论】:

  • 提供在 ArrayList 中添加图书对象的代码

标签: java arraylist return


【解决方案1】:

您正在创建 Book 和 CD 的单个实例:

   Book booka = new Book();
   CD cda = new CD();

然后,您一次又一次地将同一个实例添加到列表中,每次都更改其属性。这就是为什么您会看到所有元素都具有相同的值(最后添加的元素的值)。

您应该为每次将元素添加到其中一个列表时创建一个新实例。

例如:

     if (input.equals("1")){
         System.out.println("Input new book: ");
         input = reader.nextLine();
         Book booka = new Book(); // add this
         booka.setName(input);
         books.add(booka); input ="1";
    }

【讨论】:

    【解决方案2】:
    booka.setName(input);
    books.add(booka); input ="1";
    

    这就是问题所在!您每次都添加相同的名称而不是 booka,因此您设置为 booka 的姓氏是 ArrayList 中对它的每个引用都将返回的名称!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-07
      • 2021-07-13
      • 1970-01-01
      • 2016-05-24
      • 2018-04-10
      相关资源
      最近更新 更多