ItemArray.checklist.add()不附加字符串到ArrayList

问题描述:

我一直在学习Java大约3天,但我似乎无法追加数据到我的ArrayList(清单)之一。尝试显示数组内所有项目时的输出始终为[]。帮助将大大赞赏!ItemArray.checklist.add()不附加字符串到ArrayList

ShopAssist.java:

import java.io.*; 
import java.util.Scanner; 

    class ShopAssist { 
     public static void main(String[] args){ 
      //Items itemchecklist = new Items(); 
      System.out.println("(Add | Remove | Show | Exit)"); 
      System.out.print(">"); 
      Scanner menuinput = new Scanner(System.in); 
      String choice = menuinput.nextLine(); 
      if (choice.equals("Add")){ 
       AddItem(); 
      } 

      else if (choice.equals("Remove")){ 
       RemoveItem(); 
      } 
      else if (choice.equals("Show")){ 
       ShowItems(); 
      } 

     while(true){ 
      main(null); 
     } 
     } 

     public static void AddItem(){ 
      Items ItemArray = new Items(); 
      System.out.print("Add: "); 
      Scanner addinput = new Scanner(System.in); 
      String addchoice = addinput.nextLine(); 
      ItemArray.checklist.add(addchoice); 
      System.out.println("Info: " + addchoice + " has been added to checklist!"); 
     } 

     public static void RemoveItem(){ 
      System.out.println("RemoveItem Method"); 
     } 

     public static void ShowItems(){ 
      Items ItemArray = new Items(); 
      System.out.println("ShowItems Method"); 
      System.out.println(ItemArray.checklist); 
     } 
    } 

Items.java:

import java.util.ArrayList; 
public class Items { 
    ArrayList<String> checklist = new ArrayList<String>(); 

} 
+0

这行打印出来是什么? 'System.out.println(“Info:”+ addchoice +“已被添加到清单!”);' – Shark

+0

您在每种方法中都有一个新数组,因此它总是只显示[]。只需创建一个全球。 – Pintang

创建的ItemArray多个实例。
都在AddItem()ShowItems()。 所以你从来没有在这些方法中使用相同的实例。

应该写一次:

Items ItemArray = new Items(); 

,成为无论是传递参数给这些方法或类的字段。

理想情况下,这应该是一个private实例字段,你应该将static方法变成实例方法:

class ShopAssist { 

    private Items items = new Items(); 
    ... 

    public static void main(String[] args){ 

     ShopAssist shopAssist = new ShopAssist(); 

     while (true) { 
     System.out.println("(Add | Remove | Show | Exit)"); 
     System.out.print(">"); 
     Scanner menuinput = new Scanner(System.in); 
     String choice = menuinput.nextLine(); 

     if (choice.equals("Add")) { 
      shopAssist.addItem(); 
     } 
     else if (choice.equals("Remove")) { 
      shopAssist.removeItem(); 
     } 
     else if (choice.equals("Show")) { 
      shopAssist.showItems(); 
     } 
     } 
    } 

    public void addItem(){ 
     ... 
    } 
    ... 
    public void showItems(){   
     System.out.println("ShowItems Method"); 
     System.out.println(items.checklist); 
    } 
    ... 
} 

使用static无处不在OOP。

+0

我在哪里放置“private Items items = new Items();” – ACiDRAiN

+0

作为示例中的声明字段。我更新为更详尽。 – davidxxx

+0

是的,但添加一些东西后数组仍然是空的 – ACiDRAiN