代码之家  ›  专栏  ›  技术社区  ›  Aleo111

在java中向对象数组添加更多变量

  •  0
  • Aleo111  · 技术社区  · 3 年前

    我的一个项目搞得一团糟。我必须创建一个对象数组。我制作了一个数组,但它只有一个字段“myMonths”,表示项目的时间长度。 在我的主要方法中:

    case 1:
    
        int n = 1;    //int n = number of projects
        Scanner sc = new Scanner(System.in);
    
        //myMonths = new int[amount];
    
        System.out.println("** Only projects with a duration between 2 and 12 months can be included **");
        System.out.println("What was the duration of your projects in months?");
    
        for(int i=0; i<1; i++){
            int a = sc.nextInt();
    
            //display error message
            if((a < 2) || (a > 12)){
                System.out.println(" Please enter an amount between 2 and 12 months. ");
            }
    
            //add to the array
            else{
                myMonths[index++] = a;
            }
        }
    
        calc.setMyMonths(myMonths); //creating the object
        break;
    

    在我的课堂上,单独归档:

    public class MenuTestClass{
    
    private int myMonths[];
    private double average; //store average value of numbers
    private boolean averageCanBeCalculated;
    private int max; // store max number from array. to be calculated
    
    public MenuTestClass(){
        myMonths = new int[5];
        }
    
     public MenuTestClass(int[] myMonths){
       this.myMonths = myMonths;
       }
     public void setMyMonths(int[] values){ //declare setter method
       myMonths = values;
       }
    

    我应该再加两个字段,两个字符串。有没有一种方法可以将更多字段/属性添加到此数组中,并在1个索引下同时查看它们?例如,在[0]projectName、projectManager、myMonths ie(字符串、字符串、整数)。 任何建议都很好,我对OOP感到非常困惑。提前谢谢!

    1 回复  |  直到 3 年前
        1
  •  1
  •   Johan Nordlinder    3 年前

    是的,创建一个包含三个属性的类:

    class MyContainer {
        
        public MyContainer(int durationMonths, String projectName, String projectManager) {
            this.durationMonths = durationMonths;
            this.projectName = projectName;
            this.projetManager = projectManager;
        }
    
        public int durationMonths;
        public String projectName;
        public String projectManager;
    }
    

    然后使用以下命令创建此类的数组:

    MyContainer[] myArray = new MyContainer[numberOfProjects];
    

    向数组中添加如下项:

    myArray[0] = new MyContainer(3, "super project", "awesome manager");