简体   繁体   中英

How do I print a variable in java with an index added to the variable name?

This is what I want to do in python, but I don't know how to do it in Java. I have an object called LogRecord and I have different instances of it saved as record1, record2, record3 etc. But I want to make a for loop that will print all of them out by incrementing i by 1 each time. Sorry if this sounds stupid, just don't know how to do it. Read my example below and hopefully you can understand my problem

LogRecord record1 = new LogRecord (1, "20200301");
LogRecord record2 = new LogRecord (2, "20200302");

for (int i = 0; i < logIndex; i++) {
        System.out.println("");
        System.out.print(record1.logIndex + "  ");
        System.out.print(record1.date + ", ");

Instead of printing record1, I want it to print record1 then record2 and so on. Tried to simplify it a bit. Sorry if this question is stupid and ignore my amateur code thanks:)

Instead of using multiple variables, you should use either a list or an array of LogRecords and access individual elements with .get . For instance:

List<LogRecord> records = new ArrayList<LogRecord>();
records.add(new LogRecord(1, "20200301"));
records.add(new LogRecord(2, "20200302"));
for (int i = 0; i < records.size(); i++) {
    System.out.println("");
    System.out.print(records.get(i).logIndex + "  ");
    System.out.print(records.get(i).date + ", ");
}

This code can be further simplified by using a for-each loop to iterate through all the elements:

for (LogRecord record : records) {
    System.out.println("");
    System.out.print(record.logIndex + "  ");
    System.out.print(record.date + ", ");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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