2015-04-02 63 views
2

当我尝试打印出rec.report()时,有没有办法在for循环后访问对象“rec”?在for循环中访问对象/变量

(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'的。 https://www.google.com/search?q=java+scope&ie=utf-8&oe=utf-8#safe=off&q=java+variable+scope解决方法是在外部定义对象'BmiRecord rec = null' 'for'循环,然后只在循环内分配它。然后,可以在循环终止后使用它 – Kon 2015-04-02 15:40:43

+0

Rec在循环内部定义。所以外面就不存在了。 – shibley 2015-04-02 15:41:22

+0

每件事物都有一个范围,除此之外不可见。在这种情况下,for循环有一个由花括号分隔的作用域 – Andrea 2015-04-02 15:41:41

回答

2

您不能访问该对象REC外的for循环,因为该对象的范围只在for循环有效。正如您在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); 
} 
+0

有没有办法访问对象“rec”? – 2015-04-02 15:45:19

+0

@MichaelMiller参考编辑的答案。 – Touchstone 2015-04-02 15:52:29

+0

一个数组没有错,但是使用Collection代替几乎总是更好的决定。只是一个说明,不需要更新你的答案:)。 – Tom 2015-04-02 16:30:33

1

由于recfor循环内定义的专用变量。要访问范围之外,您需要在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());