Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 访问for循环内的对象/变量_Java_Loops_Variables_Object_For Loop - Fatal编程技术网

Java 访问for循环内的对象/变量

Java 访问for循环内的对象/变量,java,loops,variables,object,for-loop,Java,Loops,Variables,Object,For Loop,当我尝试打印rec.report()时,是否有方法在for循环之后访问对象“rec” (Report()是类内返回新计算结果的方法) for(int i=0;i您无法访问for循环外部的对象rec,因为该对象的范围仅在for循环中有效。因为您已在for循环内部创建了该对象 您可以将此与另一个问题联系起来。为什么不能在另一个函数中访问函数内部定义的局部变量 请参阅以下代码: BmiRecord rec[]=new BmiRecord[limit]; for(int i=0; i<limit

当我尝试打印rec.report()时,是否有方法在for循环之后访问对象“rec”

(Report()是类内返回新计算结果的方法)


for(int i=0;i您无法访问for循环外部的对象rec,因为该对象的范围仅在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);
}
BmiRecord rec[]=新的BmiRecord[限制];

for(int i=0;i,因为
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());
bmi记录记录记录;

对于(inti=0;i您正在访问超出范围的循环之外的对象,请尝试以下操作

    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());
bmi记录rec=null;
对于(int i=0;i
因为
范围
。解决方法是为
循环定义对象
bmirect rec=null
外部,然后只在循环内部分配它。然后在循环内部定义循环终止后可以使用它。因此,它在外部不再存在。每个对象都有一个范围,在该范围之外不可见。在本例中,for循环的作用域由花括号分隔。执行@Kon编写的操作,或创建一个集合,如“List records=new ArrayList();”,然后将记录添加到其中:“records.add(rec);”。稍后,您可以在该列表上进行迭代(可以在Google或Stackoverflow上找到示例)打印每个条目。是否有任何方法访问对象“rec”?数组没有错,但使用集合几乎总是更好的选择。只需一个注释,无需更新您的答案:)。您是对的。但是,OP似乎是该语言的新手,这就是我跳过集合部分的原因。
    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());