从ProductDB类过滤器中删除,并避免从列表

时间:2019-01-22 16:08:14

标签: java

我是Java编程专业的初学者。 下面是我的程序,正在获取 ArrayIndexOutOfBoundsException ,我试图解决该问题并进行了努力,但是有什么更好的方法来避免它。

Main.java

package com.example.java;

public class Main {
    public static void main(String[] args) {
        Product.initAll();
        for (int i = 0; i <Product.All().size() ; i++) {
            System.out.println(Product.get(i));
        }
    }
}

Product.java

package com.example.java;

public class Product extends ProductDB{
    private String mName;
    private String mDescription;
    private double mPrice;

    Product(String name, String description, double price) {
        mName = name;
        mDescription = description;
        mPrice = price;
    }

    private String getName() {
        return mName;
    }

    private String getDescription() {
        return mDescription;
    }

    private double getPrice() {
        return mPrice;
    }

    @Override
    public String toString() {
        return "mName=\""+ getName()+"\" mDescription=\""+ getDescription()+"\" mPrice=\""+ getPrice()+"\"";
    }
}

ProductDB.java

我尝试使用if条件过滤索引,它也可以工作。但是在ProductDB类本身中是否有更好的简洁方法。

package com.example.java;

import java.util.ArrayList;
import java.util.List;

class ProductDB {
    private static List<Product> products;

    static void initAll() {
        products = new ArrayList<>();
        products.add(new Product("Chair","Sit on Chair",10.11));
        products.add(new Product("Table","Dance over Table",43.16));
        products.add(new Product("Camera","Pose like a model",43.16));
        products.add(new Product("SmartPhone","Pout for a selfie",43.16));
        products.add(new Product("Computer","Play video games",43.16));
        products.add(new Product("Bag","Pack clothes for trekking",43.16));
        products.add(new Product("Pot","Plant a beautiful Rose",43.16));
        products.add(new Product("Iron","Flatten your clothes without wrinkle",43.16));
        products.add(new Product("Password","Create a strong and weird password",43.16));
        products.add(new Product("Java","Practice 1 hour every day",43.16));
    }

    static List<Product> All() {
        return products;
    }
    //here
    static Product get(int index){
        if (index >= All().size() || index < 0) {
            System.out.println("Index range should be within range of 0 - "+(All().size()-1));
            System.exit(1);
        }
        return products.get(index);
    }
}

0 个答案:

没有答案