【问题标题】:Throwing custom exceptions when using an attribute to find an object in java使用属性在java中查找对象时抛出自定义异常
【发布时间】:2018-03-29 18:20:58
【问题描述】:

我正在编写一个程序,我必须在其中创建一个方法,该方法通过与之关联的注册号来查找 CustomerAccount 对象。 当在 CustomerAccount 对象的 ArrayList 中找不到注册号时,我还需要使用自定义异常。

我的方法在尝试搜索无效注册号时抛出异常,但在搜索有效注册号时不打印任何内容。
我希望该方法输出与正确客户帐户关联的所有属性。

这是我目前的方法:

public CustomerAccount findCustomer(String regNum){

    CustomerAccount correctAccount = new CustomerAccount("","",null,0);

    for (int i = 0; i < this.customerAccounts.size(); i++) {

        if (regNum.equals(customerAccounts.get(i).getTypeOfVehicle()
                .getRegNum())) {
            correctAccount = customerAccounts.get(i);
            return correctAccount;

        } else {

            try {

                throw new CustomerNotFoundException("Customer Not Found");

            } catch (CustomerNotFoundException e) {
                    e.printStackTrace();
            }
        }

    }

    return correctAccount;

}

我是一名新程序员,所以如果答案很明显,我深表歉意,但在浏览论坛一段时间后我仍然无法弄清楚!

【问题讨论】:

  • CustomerAccount 上实现toString 方法并打印。另外,标题不代表问题
  • customerAccounts 是什么类型的对象?此外,您应该重新检查使用 try/catch 子句的方式。

标签: java exception arraylist custom-exceptions


【解决方案1】:

你需要在你的CustomerAccount中实现“toString()

类似这样的:

public class CustomerAccount {
    private String id;
    private String name;
    private String email;

    public CustomerAccount(String id, String name, String email) {
        this.id = id;
        this.name = name;
        this.email = email;
    }

    @Override
    public String toString() {
        return "CustomerAccount{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

然后你可以像这样使用它:

CustomerAccount customerAccount = new CustomerAccount("1","TestUser", "TestMail");
System.out.println(customerAccount.toString());

【讨论】:

  • 我试过了,但是在搜索有效的注册号时该方法仍然没有返回任何内容
猜你喜欢
  • 2019-06-02
  • 2015-04-25
  • 2016-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
  • 2016-02-17
相关资源
最近更新 更多