【问题标题】:Creating custom class in java, using try-catch blocks, filewriter and printwriter在 java 中创建自定义类,使用 try-catch 块、filewriter 和 printwriter
【发布时间】:2014-05-16 00:24:12
【问题描述】:

试图用 try-catch 块包围这段代码。但是,在许多不成功的尝试中,当用户输入小于 0 的余额时,我仍然无法让它抛出我的 CUSTOM 异常消息。我试图保持它非常简单以用于学习目的。我主要抛出 IOException 和 InvalidException 但是我似乎无法弄清楚如何调用自定义异常消息。我删除了它,这样代码对这里的查看者来说看起来更简单。关于我应该如何纠正这个问题的任何逻辑建议?任何反馈表示赞赏。

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

public class TestAccountWithException 
{

    public static void main(String[] args) throws IOException, InvalidBalanceException 
    {
        // variable declaration
        String fileName;
        String firstName;
        String lastName;
        double balance;
        int id = 1122;
        final double RATE = 4.50;

        Scanner input = new Scanner(System.in);
        System.out.print("Please enter file name: ");
        fileName = input.next();
        File fw = new File(fileName);

        // check if file already exists
        while(fw.exists()) 
        {
            System.out.print("File already exists, enter valid file name: ");
            fileName = input.next();
            fw = new File(fileName);
        }   


        System.out.print("Enter your first name: ");
        firstName = input.next();

        System.out.print("Enter your last name: ");
        lastName = input.next();

        // combine first and last name
        String fullName = firstName.concat(" " + lastName);

        System.out.print("Input beginnning balance: ");
        balance = input.nextDouble();   

        // pass object to printwriter and use pw to write to the file
        PrintWriter pw = new PrintWriter(fw);

        // print to created file
        pw.println(firstName);
        pw.println(lastName);
        pw.println(balance);
        pw.println(id);
        pw.println(RATE);

        AccountWithException acctException = new AccountWithException(fullName, balance, 1122, 4.50);
        System.out.println(acctException.toString());   
    } // end main
} // end class





    //  Account with exception class 

    public class AccountWithException {
      private int id;
      private double balance;
      private static double annualInterestRate;
      private java.util.Date dateCreated;
      // CRE additions for lab assignment
      private String name;

      // no-arg constructor to create default account
      public AccountWithException() {
        this.dateCreated = new java.util.Date();
      }

      // constructor for test account with exception that takes in arguments
      public AccountWithException(String newName, double newBalance, int newId, double newRate) {
          this.name = newName;
          this.balance = newBalance;
          this.id = newId; 
          AccountWithException.annualInterestRate = newRate;
          this.dateCreated = new java.util.Date();
      }

      // accessor methods
      public int getId() {
        return this.id;
      }

      public double getBalance() {
        return this.balance;
      }

      public static double getAnnualInterestRate() {
        return annualInterestRate;
      }

      public double getMonthlyInterest() {
        return this.balance * (this.annualInterestRate / 1200);
      }

      public java.util.Date getDateCreated() {
        return this.dateCreated;
      }

      public String getName() {
        return this.name;
      }

      // mutator methods
      public void setId(int newId) {
        this.id = newId;
      }

      public void setBalance(double newBalance) throws InvalidBalanceException {

          if(balance >= 0) {
            this.balance = newBalance;
          }
          else {
            throw new InvalidBalanceException(balance);
          }
      }   

      public static void setAnnualInterestRate(double newAnnualInterestRate) {
        annualInterestRate = newAnnualInterestRate;
      }

      public void setName(String newName) {
        this.name = newName;
      }

      // balance modification methods
      public void withdraw(double amount) {
        this.balance -= amount;
      }

      public void deposit(double amount) {
        this.balance += amount;
      }

      // override of Object method
      public String toString() {
        // return string with formatted data 
        // left-align 20 character column and right-align 15 character column
        return String.format("%-20s%15d\n%-20s%15tD\n%-20s%15s\n%-20s%15.2f%%\n%-20s%,15.2f\n",
          "ID:", this.id,
          "Created:", this.dateCreated,
          "Owner:", this.name,
          "Annual Rate:", this.annualInterestRate,
          "Balance:", this.balance);
      }
    }



public class InvalidBalanceException extends Exception {

    private double balance;

    public InvalidBalanceException(double balance) {
        // exceptions constructor can take a string as a message
        super("Invalid Balance " + balance);
        this.balance = balance;
    }

    public double getBalance() {
        return balance;
    }

}

【问题讨论】:

    标签: java try-catch filewriter printwriter custom-exceptions


    【解决方案1】:

    您正在从 setBalance() 方法中抛出异常,但您没有在构造函数中调用它。您只是直接在成员变量上设置值。

    试试这个:

    // constructor for test account with exception that takes in arguments
    public AccountWithException(String newName, double newBalance, int newId, double newRate) throws InvalidBalanceException {
        setName(newName);
        setBalance(newBalance);
        setId(newId);
        setAnnualInterestRate(newRate);
        this.dateCreated = new java.util.Date();
    }
    

    另外,您的setBalance 方法不起作用,您正在检查现有余额是否非法,而不是新值。

    试试这个:

    public void setBalance(double newBalance) throws InvalidBalanceException {
        if (newBalance >= 0) {
            this.balance = newBalance;
        } else {
            throw new InvalidBalanceException(balance);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2011-08-11
      • 2012-12-13
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      相关资源
      最近更新 更多