2017-10-16 120 views
0

所以我有两个类,一个叫bag另一个叫TestBag。目标是询问用户他们想要什么:添加或删除,并显示他们在购物车中的内容。Java数组封装

我有点新来封装,我不知道如何获得用户输入,并把它放在添加方法,并得到这个去购物车字符串来显示用户在购物车中有什么。这是我迄今为止所拥有的。在删除之前,我正在执行添加部分。

袋类:

import java.util.Arrays; 

class bag { 
    private String[] cart = new String[5]; 
    private int add; 


    public String[] getcart(){ 
     return Arrays.copyOf(cart, getcart().length); 
    } 

    public int getAdd(){ 
     return add; 
    } 


    public void setAdd(int newValue){ 
     add = newValue; 

    } 

    public void setcart(String [] cart){ 
     cart = cart; 
    } 


} 

TestBag:

import java.util.Scanner; 

public class TestBag { 

    public static void main(String[] args) { 
     bag obj = new bag(); 

     System.out.println("Enter one of the following commands:"); 
     System.out.println("1 - add"); 
     System.out.println("2 - remove"); 
     System.out.println("3 - exit"); 
     Scanner input = new Scanner(System.in); 
     System.out.println(); 
     System.out.println("Enter \"1\", \"2\" or \"3\""); 
     int choice =input.nextInt(); 




     while (choice != 3) { 
      if(choice == 1) { 
       System.out.println("What do you want to add? "); 

       for (int i = 0 ; i < obj.setAdd.length; i++) { 
       obj.setAdd[i] = input.nextInt(); 
       } 
       System.out.println("Here's whats in your cart: "); 
       printArray(obj.getcart()); 


      } 
      else if(choice == 2) { 
       //remove 
      } 
      else if(choice == 3) { 
       //...exit program 
      } 
      else{ 

       System.out.println("Enter \"1\", \"2\", \"3\""); 
       choice = input.nextInt(); 

      } 

     } 
    } 

} 
+3

更好地使用'list'而不是'array',只是一个建议。 – msagala25

+2

1. class'bag'应该叫大写的'Bag' B. 2.这段代码不编译 - 先修正编译错误!你可以从修复开始:'obj.setAdd.length'你在那里做了什么? – alfasin

+0

如果你不能使用'List' /'ArrayList'(就像因为它是一项家庭作业),那么你需要保留某种'count',这样你就知道每次调用'add'时哪一个索引要放下一个数组中的元素。 – markspace

回答

0

感谢您分享您的代码。看着你的包类,你试图通过数据隐藏,以实现封装:

  1. 声明一个类的变量为私有。

  2. 提供公共setter和getter方法来修改和查看变量值。

然而,声明getter和setter这种方式暴露你声明为在第一步私有变量。那么,吸气剂就好了,因为人们必须看到购物车的内容和购物车中的物品数量。制定者不好。这就像通过设置者声明你的变量是公开的,你可以随时修改它们。

通过数据隐藏进行封装的主要点是对限制访问该类的变量以选择方法。以下是我如何去做:

public class Bag{ 
    //Assuming that the bag has a dynamic size, a list would be appropriate here 
    public List<String> items; 

    public Bag(){ 
     items = new ArrayList<String>(); 
    } 

    //This modifies the contents of the bag. The modification is restricted 
    //through one of the methods (adding an item into the bag) 
    //that are really part of the task. 
    public void add(String item){ 
     items.add(item) 
    } 

    public List<String> getItems(){ 
     return new ArrayList<String>(items); 
    } 

    public int getNumberOfItems(){ 
     return items.size(); 
    } 
}