使用do-while循环将用户输入添加到ArrayList

时间:2018-12-18 16:39:38

标签: java arraylist bluej

我正在尝试使用do-while循环将用户输入添加到Arraylist中,但是我最终得到的列表仅包含重复输入多次的最终项目。

public static ArrayList<Item> purchaseItems()
       {
        ArrayList<Item> toBuy = new ArrayList<Item>();

        String response;
        System.out.println("What would you like to purchase? (type \"done\" to end) ");   
        do {

             response = in.nextLine();
             if(!response.equals("done") ){

                    toBuy.add(new Item(response, randGen.nextInt(100)));
                    System.out.println(toBuy);
            }

        } while(!response.equals("done"));

        return toBuy;
    }

2 个答案:

答案 0 :(得分:0)

应该按我的评论中所述工作。 如果尚未完成,请在您的Item类中实现toString()方法。 您应按以下方式替换System.out.println:

    public static ArrayList<Item> purchaseItems()
           {
            ArrayList<Item> toBuy = new ArrayList<Item>();

            String response;
            System.out.println("What would you like to purchase? (type \"done\" to end) ");   
            do {

                 response = in.nextLine();
                 if(!response.equals("done") ){

                        toBuy.add(new Item(response, randGen.nextInt(100)));
                }

            } while(!response.equals("done"));

               for (Item item : toBuy){
               System.out.println(item);
                }
            return toBuy;
        }

如果这样做没有帮助,请共享更多代码。

答案 1 :(得分:0)

这是一个完全正常的示例

package stackoverflow;

import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;

public class Q53837506 {

    public static void main(String[] args) {
        ArrayList<Item> purchaseItems = purchaseItems();
        System.out.println(purchaseItems);

    }

    public static class Item {
        String r;
        int v;

        public Item(String r, int v) {
            super();
            this.r = r;
            this.v = v;
        }

        @Override
        public String toString() {
            return "Item [r=" + r + ", v=" + v + "]";
        }
    }

    static final Random randGen = new Random();

    public static ArrayList<Item> purchaseItems() {
        ArrayList<Item> toBuy = new ArrayList<Item>();

        String response;
        System.out.println("What would you like to purchase? (type \"done\" to end) ");
        Scanner in = new Scanner(System.in);
        do {

            response = in.nextLine();
            if (!response.equals("done")) {

                toBuy.add(new Item(response, randGen.nextInt(100)));
                System.out.println(toBuy);
            }
        } while (!response.equals("done"));

        return toBuy;
    }
}