我有一个愚蠢的试题,在这个试题中,我被告知要用主要的方法制作一系列的对象。我用两个变量定义了类Account
-- String和double and。
然后,我被告知让帐户类处理所有金额的值和的变化。等等,但我不知道我做错了什么-我无法从getAmount()
访问数组。
public static void main(String[] args)
{
Account[] account = new Account[10];
for ( int i=0; i<account.length; i++)
{
account[i]=new Account();
}
account[0].owner = "Thomas";
account[0].amount = 24325;
System.out.println(getAmount(0)); //<- dont work, but works with account[0].amount
}
public static double getAmount(int x)
{
double s = account[x].amount; //<<------- CANNOT FIND SYMBOL
return s;
}
发布于 2014-11-09 09:11:28
account
是主方法的本地方法,因此不能从其他方法访问它,除非作为参数传递给它们。
另一种方法是将其声明为静态成员:
static Account[] account = new Account[10];
public static void main(String[] args)
{
for ( int i=0; i<account.length; i++)
{
account[i]=new Account();
}
account[0].owner = "Thomas";
account[0].amount = 24325;
System.out.println(getAmount(0));
}
发布于 2014-11-09 09:27:25
在本例中,帐户是main的局部变量,如果要使用getAmount方法,您有两个选项:将数组作为静态-Declare并将其从main方法(数组将是全局变量)中剔除出来,将数组作为getAmount中的一个参数。
public static void main(String[] args)
{
Account[] account = new Account[10];
for ( int i=0; i<account.length; i++)
{
account[i]=new Account();
}
account[0].owner = "Thomas";
account[0].amount = 24325;
System.out.println(getAmount(0), account); //<- dont work, but works with account[0].amount
}
public static double getAmount(int x, Account[] account)
{
double s = account[x].amount; //<<------- CANNOT FIND SYMBOL
return s;
}
https://stackoverflow.com/questions/26826697
复制相似问题