英文:
How do I print a variable in java with an index added to the variable name?
问题
这是我想在Python中实现的内容,但我不知道如何在Java中实现。我有一个名为LogRecord的对象,并且我有不同的实例保存为record1、record2、record3等。但我想要创建一个for循环,通过每次将i增加1来打印出所有这些实例。如果听起来很愚蠢,我很抱歉,我只是不知道怎么做。请阅读下面的示例,希望您能理解我的问题。
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 + ", ");
}
我希望它不仅打印record1,还要依次打印record1、然后record2,依此类推。尝试了一下,希望问题表述得更简单些。如果这个问题听起来愚蠢,请忽略我业余的代码,谢谢
英文:
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
答案1
得分: 0
代替使用多个变量,您应该使用列表或LogRecords
数组,并使用.get
访问单个元素。例如:
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 + ", ");
}
可以进一步简化这段代码,使用for-each循环遍历所有元素:
for (LogRecord record : records) {
System.out.println("");
System.out.print(record.logIndex + " ");
System.out.print(record.date + ", ");
}
英文:
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 + ", ");
}
专注分享java语言的经验与见解,让所有开发者获益!
评论