简体   繁体   English

如何在 java 中打印变量并在变量名中添加索引?

[英]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.这是我想在 python 中做的,但我不知道如何在 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.我有一个名为 LogRecord 的 object,我将它的不同实例保存为记录 1、记录 2、记录 3 等。但我想创建一个 for 循环,通过每次将 i 增加 1 将它们全部打印出来。 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.而不是打印record1,我希望它先打印record1,然后再打印record2,依此类推。 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 .而不是使用多个变量,您应该使用LogRecords的列表或数组并使用.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-each 循环遍历所有元素,可以进一步简化此代码:

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

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

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