Is there a way to access the object "rec" after the for loop when I try to print out rec.report()?
(Report() is a method inside of the class BmiRecord that returns new calculated results).
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());
You cannot access the object rec outside the for loop because the scope of the object is only valid in the for loop. As you have created that object inside the for loop.
You can relate this with another question. Why can't you access the local variable defined inside a function in another function?
Refer the following code:
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With