无法让程序在java中正确显示

时间:2014-04-07 01:59:47

标签: java printwriter

所以我试图在我的AccountWithException类中调用我的toString方法来打印文件中包含的用户输入,但由于某种原因我无法破解它为什么不打印。我试图做System.out.println(pw.toString())..只是为了让我不断打印内存位置。最初我只是回读文件,但我的教师指定了这个:“使用重载的toString方法输出到控制台和文件(通过PrintWriter)”我使用重载的toString作为我的对象,但无法找到我的文件。在我的代码中是否有一些我忽略的东西或者这是一个简单的Sysout.println()语句?已添加要求。

1。)提示用户输出文件名。为文本输出创建一个文件。

2。)如果文件存在则提示用户输入新文件名。在输入有效的非现有文件名并打开文件进行输出之前,请勿继续。

3。)提示用户输入名字,姓氏,余额,(账户ID和年利​​率可以是常数)

4.。)创建包含用户指定数据的AccountWithExceptionObject。

5.如果对象中存在有效数据:将对象信息输出到显示器AS以及打开的输出文件。输出数据时使用重载的toString()方法。如果存在无效数据(< 0),则抛出自定义InvalidBalanceException。

6。)使用finally块确保输出文件已正确关闭。

import java.util.Scanner;
import java.io.File;
//import java.io.FileNotFoundException;
//import java.io.IOException;
import java.io.PrintWriter;
//import java.io.FileReader;
//import java.io.BufferedReader;

public class TestAccountWithException {

    public static void main(String[] args) throws InvalidBalanceException, FileNotFoundException, IOException {
        // 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 a file name: ");
        fileName = input.next();
        File fw = new File(fileName + ".txt");

        // while loop to 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 + ".txt");
        }

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

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

        // concatanate full/last name
        String fullName = firstName.concat(" " + lastName);

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

        PrintWriter pw = null;
        // pass object to printwriter and pw to write to the file
        pw = new PrintWriter(fw);
        // print to created file
        pw.println(firstName);
        pw.println(lastName);
        pw.println(balance);
        pw.println(id);
        pw.println(RATE);


        String line = null;


        try {

            // pass user input to object
            AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);

            System.out.println(acctException.toString());


            // create the object
            //FileReader fr = new FileReader(fileName + ".txt");
            // pass to buffered reader and use its preset commands for alteration to file
            //BufferedReader br = new BufferedReader(fr);
            //System.out.println("Text file opened and reading...");

            // read in lines from file
        //  while ((line = br.readLine()) != null) {
                //System.out.println(line);
            //}
            // close buffered reader
            //br.close();

            // custom exception if balance < 0
        } catch (InvalidBalanceException e) {
            System.out.println(e.getMessage());
        //} catch (FileNotFoundException e) {
            //System.out.println("File not found" + fileName);
        //} catch (IOException e) {
            //System.out.println(e.getMessage());
        } finally {
            System.out.println("Text file closing...");
            pw.close();

        }

    } // end main
} // end 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) throws InvalidBalanceException {
       setName(newName);
       setBalance(newBalance);
       setId(newId);
       setAnnualInterestRate(newRate);
       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(newBalance >= 0) {
        this.balance = newBalance;
      }
      else {
        throw new InvalidBalanceException(newBalance);
      }
  }   

  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;
    }



}

1 个答案:

答案 0 :(得分:0)

尝试在你的tostring方法上打一个@Override。

  // override of Object method
  @Override
  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);
  }
}

此外,在命名类时,如果它们抛出异常,则不应对其进行“WithException”。这个班应该只是“帐户”。