简体   繁体   English

如何遍历对象的 ArrayList 并使其打印所有内容?

[英]How to loop through ArrayList of objects and make it print everything?

A few days ago I asked this question, and now I have a more specific one, since I worked on my program some more and added a few things.几天前我问了这个问题,现在我有了一个更具体的问题,因为我在我的程序上做了更多的工作并添加了一些东西。 Basically I start out with an empty ArrayList which is supposed to hold birthdays that are added via console.基本上我从一个空的 ArrayList 开始,它应该保存通过控制台添加的生日。 This part I got down + it prints the birthday I add.这部分我下来了+它打印了我添加的生日。 But if I want to add another one, it prints the first one I added again?但是如果我想添加另一个,它会打印我再次添加的第一个? How could I make it print out all the birthdays I have added this far?我怎样才能让它打印出我到目前为止添加的所有生日? I'll show the code I have so far我将展示我到目前为止的代码

Birthday class生日 class

public class Birthday {
    private String bdayKid;
    private int age;
    private boolean gift;
    
    public Birthday(String bdayKid, int age, boolean gift) {
        this.bdayKid = bdayKid;
        this.age = age;
        this.gift = gift;
    }
    
    //overridden toString() method
    public String toString() { 
        return this.bdayKid + " turns " + this.age + "! They are" + 
            (this.gift ? "" : "not ") + " getting a gift.";
    }
}

Main class主class

public class MainClass{
   public static void main(String []args) {
      ArrayList<Birthday> bdays = getBirthdays();
      printBirthdays(bdays);
   }

   //This method will return a list of birthdays
   public ArrayList<Birthday> getBirthdays() { 
      ArrayList<Birthday> bdays = new ArrayList<Birthday>();
      Scanner scan = new Scanner(System.in);
      
      //create a birthday
      Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
      //add the birthday to arraylist of birthdays
      bdays.add(bday);

      
      return bdays;
   }

   //This method will print a list of birthdays
   public void printBirthdays(ArrayList<Birthday> bdays) {    
      //iterate through each birthday and print out the result 
      for (Birthday bday : bdays) {
         System.out.println(bday);
      }
   }
}

and inside a long-ish switch statement i added this option:在一个长长的 switch 语句中,我添加了这个选项:

System.out.println("Do you want to add another birthday?");
                    boolean anotherOne = scan.nextBoolean();
                    if (anotherOne == true) {
                        getBirthdays();
                        printBirthdays(bdays);
                    }

Do I need to add an if statement inside my for-each loop?我是否需要在我的 for-each 循环中添加一个 if 语句? Any help is appreciated!任何帮助表示赞赏!

You have a serious problem in understanding Java .您在理解Java方面存在严重问题。 First, you need to understand a concept, the scope of a variable.首先,你需要了解一个概念,变量的scope。

If you create a variable inside a function, then the scope of the variable is in the function only.如果在 function 中创建变量,则变量的 scope 仅在 function 中。

You have different instances of ArrayList<Birthday> with the identifier bdays .您有不同的ArrayList<Birthday>实例,标识符bdays One instance that you defined in void main function, and other instances are created each time you call getBirthdays() method.您在void main function 中定义的一个实例,每次调用getBirthdays()方法时都会创建其他实例。 In the switch statement, when you call getBirthdays() , a new ArrayList<Birthday> is formed and returned by the function, while your original ArrayList<Birthday> bdays remains unchanged.在 switch 语句中,当您调用getBirthdays()时,function 将形成并返回一个新的ArrayList<Birthday> ,而您原来的ArrayList<Birthday> bdays保持不变。 And when you call printBirthdays(bdays) it takes argument as the array created by you in the first line of your main method instead of a new ArrayList returned by getBirthdays() method.当您调用printBirthdays(bdays)时,它会将参数作为您在 main 方法的第一行创建的数组,而不是getBirthdays()方法返回的新ArrayList Hence, it does not print the new Brithday .因此,它不会打印新的Brithday So, you can change your code something like follows:因此,您可以更改代码,如下所示:

Main class主class

public class MainClass{
   public static void main(String []args) {
      // Instantiate your one and only bdays array
      ArrayList<Birthday> bdays = new ArrayList<Birthday>();
      getBirthdays(bdays);
      printBirthdays(bdays);
   }

   //This method will return a list of birthdays
   public void getBirthdays(ArrayList<Birthday> bdays) { 
      Scanner scan = new Scanner(System.in);
      
      //create a birthday
      Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
      //add the birthday to arraylist of birthdays
      bdays.add(bday);

      // Good practice to close a scanner
      scan.close();
   }

   //This method will print a list of birthdays
   public void printBirthdays(ArrayList<Birthday> bdays) {    
      //iterate through each birthday and print out the result 
      for (Birthday bday : bdays) {
         System.out.println(bday);
      }
   }
}

and,和,

System.out.println("Do you want to add another birthday?");
                boolean anotherOne = scan.nextBoolean();
                if (anotherOne == true) {
                    getBirthdays(bdays);
                    printBirthdays(bdays);
                }

Note that, Java passes objects as reference, so if you pass you **bdays** to getBirthdays(bdays) then every change inside this function done to bdays will also occur to your original bdays in main method.请注意,Java 将对象作为参考传递,因此如果您将**bdays**传递给getBirthdays(bdays) ,则此 function 中对bdays所做的每个更改也将发生在main方法中的原始bdays中。 More precisely, they are the same ArrayList in your memory, and the variables bdays in two different methods main and getBirthdays(bdays) are just different identifiers referencing to same ArrayList<Birthday> that you created at the start of the function and passed as a reference to the getBirthdays method. More precisely, they are the same ArrayList in your memory, and the variables bdays in two different methods main and getBirthdays(bdays) are just different identifiers referencing to same ArrayList<Birthday> that you created at the start of the function and passed as a参考getBirthdays方法。 Check other relevant tutorials on passing variables by reference in java.在 java 中参考其他有关传递变量的相关教程。

IMO the best way to do this is splitting your getBirthdays() to printBirthdays() and addBirthday(). IMO 最好的方法是将你的 getBirthdays() 拆分为 printBirthdays() 和 addBirthday()。 Here is the code and you can use your own logic to loop the input:这是代码,您可以使用自己的逻辑来循环输入:

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

public class MainClass {
    static ArrayList<Birthday> bdays = new ArrayList<>();
    public static void main(String []args) {

        while(true) {
            //Use this method every time you need to add new BDay
            addBirthday();
            //Use this method to print all BDays in ArrayList
            printBirthdays();
        }
    }
    public static void addBirthday(){
        Scanner scan = new Scanner(System.in);
        Birthday bday = new Birthday(scan.nextLine(), scan.nextInt(), scan.nextBoolean());
        bdays.add(bday);
    }
    public static void printBirthdays(){
        for(Birthday b: bdays){
            System.out.println(b);
        }
    }
}

Add field in the Birthday class:Birthday class 中添加字段:

private boolean printed = false;

Then on your print function:然后在您的打印 function 上:

 //This method will print a list of birthdays
   public void printBirthdays(ArrayList<Birthday> bdays) {    
      //iterate through each birthday and print out the result 
      for (Birthday bday : bdays) {
         if(!bday.isPrinted())
         {
            System.out.println(bday);
            bday.setPrinted(true);
         }
      }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM