[英]Accessing a variable from another private method within the same class - is this possible?
我得到指示创建一个返回 Int“inputAge”的方法,条件是来自方法“run”的先前输入变量“age”大于 18。
但是,由于 Int“age”是在“run”方法中声明和定义的,我无法在从“inputAge”返回 int 的方法中访问它,因此我无法检查 Int“age”是否大于 18。
指令 state 我必须在此代码中使用“inputAge”方法,因此在“run”方法中不检查输入变量“age”是否大于 18。
这些说明是从我分配的工作表中逐字提取的(请原谅任何英语不好的老师):
"在代理示例中添加以下功能。年龄需要大于或等于 18。如果年龄小于 18,程序会再次询问,直到输入大于等于 18 的数字。你应该实现一个方法名为 inputAge 并从运行中调用该方法。方法如下(已添加在计算机实验室可用的 Java 文件中)"
public int inputAge()
{
// add the code here to receive an integer number as input and
// check if the number is greater or equal to 18
// if the number is less than 18, the program should ask the number again
// until the input number is greater or equal to 18
return(0);//note that 0 was added here just to be able to compile
}
import java.util.*;
public class AgencyInterface
{
private void run()
{
Scanner console = new Scanner(System.in);
Couple c = new Couple();
int age,end;
String name;
do {
System.out.print("first person: ");
System.out.print("name: ");
name = console.next();
System.out.print("age: ");
age = console.nextInt();
c.addData(1,name,age);
System.out.print("second person: ");
System.out.print("name: ");
name = console.next();
System.out.print("age: ");
age = console.nextInt();
c.addData(2,name,age);
System.out.println("********************");
System.out.println(c.test());
System.out.println("********************");
System.out.print("Quit? (0)yes (1)no: ");
end = console.nextInt();
}
while (end!=0);
}
public static void main(String[] args)
{
AgencyInterface agency = new AgencyInterface ();
agency.run();
}
public int inputAge()
{
// add the code here to receive an integer number as input and
// check if the number is greater or equal to 18
// if the number is less than 18, the program should ask the number again
// until the input number is greater or equal to 18
// The four comments above give instruction again what to do within here.
// They were not written by me (Lachshmock).
return(0);//note that 0 was added here just to be able to compile
}
}
看起来您需要替换出现的两个行:
System.out.print("age: ");
age = console.nextInt();
和
age = inputAge();
然后inputAge
应该是这样的:
public int inputAge()
{
int age;
do {
// Get the age from stdin. Print error if < 18
} while (age < 18);
return age;
}
我遗漏了一些东西,因为这看起来像家庭作业。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.