gpt4 book ai didi

Java 类型不匹配 : cannot convert from java. lang.Object

转载 作者:行者123 更新时间:2023-11-30 03:57:02 24 4
gpt4 key购买 nike

我正在使用 Blue Pelican Java 教科书并使用 drjava。我目前正在从事第 43 课 Big Bucks 项目,基本上我必须使用这个 BankAccount 类:

public class BankAccount
{
public BankAccount(String nm, double amt)
{
name = nm;
balance = amt;
}
public void deposit(double dp)
{
balance = balance + dp;
}
public void withdraw(double wd)
{
balance = balance - wd;
}
public String name;
public double balance;
}

并且还创建另一个类,它允许我输入多个帐户,将它们存储在数组列表中,然后确定哪个帐户拥有最大的余额。这是到目前为止我的代码:

import java.io.*;
import java.util.*; //includes ArrayList
import java.text.*; //for NumberFormat
public class BigBucks
{
public static void main(String args[])
{
NumberFormat formatter = NumberFormat.getNumberInstance( );
formatter.setMinimumFractionDigits(2);
formatter.setMaximumFractionDigits(2);
String name;
List aryLst = new ArrayList( );
do
{
Scanner kbReader = new Scanner(System.in);
System.out.print("Please enter the name to whom the account belongs. (\"Exit\" to abort)");
name = kbReader.nextLine( );
if( !name.equalsIgnoreCase("EXIT") )
{
System.out.print("Please enter the amount of the deposit. ");
double amount = kbReader.nextDouble();
System.out.println(" "); //gives an eye-pleasing blank line
BankAccount myAccount = new BankAccount(name,amount);
aryLst.add(myAccount); //add account to array list
}
}while(!name.equalsIgnoreCase("EXIT"));
//Search aryList and print out the name and amount of the largest bank account
BankAccount ba = aryLst.get(0);//get first account in the list
double maxBalance = ba.balance;
String maxName = ba.name;
for(int j = 1; j < aryLst.size( ); j++)
{
//? Step through the remaining objects and decide which one has
//largest balance (compare each balance to maxBalance)
BankAccount na = aryLst.get(j);
double nBalance = na.balance;
String nName = na.name;
if(nBalance > maxBalance)
{
maxBalance = nBalance;
maxName = nName;
}

//? Step through the remaining objects and decide which one has largest balance (compare each balance to maxBalance)
//?
}
System.out.println("The accouint with the largest balance belongs to "+ maxName + ".");
System.out.println("The amount is $" + maxBalance + ".");
}
}

但是每次我编译它时都会出现此错误

Type mismatch: cannot convert from java.lang.Object to BankAccount

在第 28 和 35 行。为什么我会收到此错误以及如何修复它???如有任何帮助,我们将不胜感激。

最佳答案

您将 BankAccount 对象存储在一个普通列表中。

List aryLst = new ArrayList( );

更改它以指定 BankAccount 对象列表。

List<BankAccount> aryLst = new ArrayList<BankAccount>( );

当使用generics时这样,尝试将 BankAccount 以外的任何内容添加到列表中都会出现编译器错误,但在访问列表元素时不必强制转换对象。

<小时/>

另一种选择(如果您使用的是 Java 5 或更高版本,则不推荐)是在访问列表时强制转换对象。

BankAccount ba = (BankAccount)aryLst.get(0);

关于Java 类型不匹配 : cannot convert from java. lang.Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22901508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com