在for循环中访问对象/变量

4

在for循环后,是否有一种方法可以访问对象"rec",以便我尝试打印出rec.report()?

(report()是类BmiRecord中返回新计算结果的方法。)

for(int i=0; i<limit; i++)
{
     int height = scanner.nextInt();
     int weight = scanner.nextInt();
     String name = scanner.nextLine();

     BmiRecord rec = new BmiRecord(name, height, weight);
} 

    System.out.println(rec.report());

2
由于“作用域(scope)”的原因。解决方法是在for循环外定义对象BmiRecord rec = null,然后在循环内部进行赋值。这样,在循环结束后就可以使用它了。 - Kon
Rec在循环内部被定义,因此它在外部不再存在。 - shibley
每个东西都有一个范围,它在外部是不可见的。在这种情况下,for循环的范围由花括号限定。 - Andrea
要么按照@Kon所写的做,要么创建一个类似于'List<BmiRecord> records = new ArrayList<>();'的集合,然后将记录添加到其中:'records.add(rec);'。稍后您可以遍历该列表(示例可在Google或Stackoverflow上找到)以打印每个条目。 - Tom
3个回答

2

由于对象的作用域仅在for循环中有效,因此无法在for循环之外访问rec对象。因为你是在for循环内创建该对象的。

你可以将其与另一个问题联系起来。为什么无法在另一个函数中访问在函数内定义的局部变量?

请参阅以下代码:

BmiRecord rec[]=new BmiRecord[limit];

for(int i=0; i<limit; i++)
{
 int height = scanner.nextInt();
 int weight = scanner.nextInt();
 String name = scanner.nextLine();

 rec[i] = new BmiRecord(name, height, weight);
} 
for(BmiRecord re:rec){
     System.out.println(re.report);
}

有没有办法访问对象“rec”? - Michael Miller
数组并没有错,但是使用集合几乎总是更好的决策。只是一点提醒,无需更新你的答案 :)。 - Tom
1
你是正确的。然而,OP似乎对这门语言很新,所以我跳过了集合部分。 - Touchstone

1

因为rec是在for循环内定义的私有变量。要在其作用域之外访问它,需要在for循环之前定义它。以下是您的新代码:

BmiRecord rec;

for(int i=0; i<limit; i++)
{
 int height = scanner.nextInt();
 int weight = scanner.nextInt();
 String name = scanner.nextLine();

 rec = new BmiRecord(name, height, weight);
} 

System.out.println(rec.report());

0

您正在访问循环外的对象,该对象超出了范围,请尝试像这样操作

    BmiRecord rec = null;
    for (int i = 0; i < limit; i++) {
        int height = scanner.nextInt();
        int weight = scanner.nextInt();
        String name = scanner.nextLine();

        rec = new BmiRecord(name, height, weight);
    }

    System.out.println(rec.report());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接