我能够输出最高的值,但是当我执行.getNames时却无法正常工作,因为它显示了一个错误
错误是我似乎无法显示关联名称的最高值,而只显示余额
//Highest Balance
Double largest = customer[0].getBalance();
for (int i=0; i<customer.length; i++)
{
if(customer[i].getBalance() > largest)
largest = customer[i].getBalance();
}
System.out.println("The highest balance is " + largest);
答案 0 :(得分:0)
我想在您的课程中必须有一个方法getName()
或类似的方法,例如getBalance()
方法:
Double largest = customer[0].getBalance();
String name = customer[0].getName();
for (int i = 1; i < customer.length; i++) {
if(customer[i].getBalance() > largest) {
largest = customer[i].getBalance();
name = = customer[i].getName();
}
}
System.out.println("The highest balance is " + largest);
System.out.println("The customer with highest balance is " + name);
由于您已经将第一项(位置= 0)的值分配给了largest
和name
,因此您也可以从第二个数组项(位置= 1)开始循环。>
答案 1 :(得分:0)
这可能会有所帮助:
Double largest = customer[0].getBalance();
String nameOfCustomer = "";
for (int i = 0; i < customer.length; i++) {
if (customer[i].getBalance() > largest) {
largest = customer[i].getBalance();
nameOfCustomer = customer[i].getName();
}
}
System.out.println("The highest balance is " + largest +
" for customer " + nameOfCustomer);
这里使用的逻辑与您找到最高余额的逻辑相同。
答案 2 :(得分:0)
您还需要存储与最大值关联的名称。您可以在更新largest
余额时更新它,也可以存储拥有最大值(和最大余额)的整个customer
对象。示例:
Double largest = customer[0].getBalance();
String name = "";
for (int i=0; i<customer.length; i++)
{
if(customer[i].getBalance() > largest)
{
largest = customer[i].getBalance();
name = customer[i].getName();
}
}
System.out.println("The highest balance is " + largest);
System.out.println("The name of the customer is " + name);