6 Replies - 1603 Views - Last Post: 05 May 2011 - 09:54 PM Rate Topic: -----

#1 tam13  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 16-June 10

Need help writing to a file

Posted 30 April 2011 - 08:07 PM

Hi Guys,
I need to write my registry to a method to write my registry to a file and then read the file back. It creates the file just fun but doesn't write any of the information to the file. Can anyone tell me why it isn't writing the information to the file.

Thanks!
import java.util.Scanner;
import java.io.*;

public class account {
	private static String name;
	private static int checkNum;
	protected static double balance;
	private static double withdraw;
	private static double deposit;
	private double withdrawAmnt;
	private double depositAmnt;
	static double newAmnt;
	static Scanner scan = new Scanner(System.in);

	public account(){
		name = null;
		checkNum = 0;
		balance = 0;
		withdraw = 0;
		deposit = 0;
	}//End constructor

	public static String getName(){
		return name;
	}//End getName

	public static void setName(String newName){
		name = newName;
	}//End setName

	public static int getCheckNum(){
		return checkNum;
	}//End getCheckNum

	public static void setCheckNum(int newCheckNum){
		checkNum = newCheckNum;
	}//End setCheckNum

	public static double getBalance(){
		System.out.println("Your balance is:" + balance);
		return balance;
	}//End getBalance

	public static void setBalance(double newBalance){
		balance = newBalance;
		//System.out.println("Your balance is :" + balance);
	}//End setBalance


	public double getWithdraw(){
		return withdraw;
	}//End getWithdraw

	public void setWithdraw(double newWithdraw){
		withdraw = newWithdraw;
	}//End setWithdraw

	public double getWithdrawAmount(){
		return withdrawAmnt;
	}//End getWithdrawAmount

	public double getDepositAmount(){
		return depositAmnt;
	}//End getDepositAmount

	public static double withdraw(){
		System.out.println("Please enter the amount you wish to withdraw:");
		withdraw = scan.nextDouble();
		newAmnt = balance - withdraw;
		if(newAmnt <= 0){
			System.out.println("ERROR: Insufficent funds!");
			System.exit(1);
		}//End if
		//System.out.println("Your new balance is:" + newAmnt);
		return balance - withdraw;
	}//End withdraw

	public static double deposit(){
		System.out.println("Please enter the amount to deposit:");
		deposit = scan.nextInt();
		newAmnt = balance + deposit;
		System.out.println("Your new balance is:" + newAmnt);
		return balance + deposit;
	}//End deposit

	public static void Registry(){
		System.out.println("Enter your id number:");
		account.setName(scan.next());
		System.out.println("Enter your check number");
		account.setCheckNum(scan.nextInt());
		System.out.println("Enter the check amount :");
		account.setBalance(scan.nextDouble());
	}//End Registry

	public static void printRegistry(){
		System.out.println("Your id is:" + account.getName());
		System.out.println("Your check number is: " + account.getCheckNum());
		System.out.println("Your balance is: " + account.getBalance());
	}//End printRegistry

	public static void fileWriter() throws IOException{
		try{
			BufferedWriter out = new BufferedWriter(new FileWriter("Account"));
			out.write(account.getName());
			out.write(account.getCheckNum());
			out.write((int) account.getBalance());
		}catch(IOException e){
			System.out.println("ERROR: Could not write to file!");
			System.exit(1);
		}
	}//End fileWriter

	public static void fileReader(){
		try{
			BufferedReader in = new BufferedReader(new FileReader ("Account"));
			String str;
			while((str = in.readLine()) != null){
				System.out.println(str);
			}
			in.close();
		}catch(IOException e){
			System.out.println("ERROR: Could not read from file!");
			System.exit(1);
		}
	}//End fileReader

	public static void main(String[] args) throws IOException{
		userInterface user = new userInterface();
		user.Driver();
	}//End Main
}//End Account


Is This A Good Question/Topic? 0
  • +

Replies To: Need help writing to a file

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10668
  • View blog
  • Posts: 39,615
  • Joined: 27-December 08

Re: Need help writing to a file

Posted 30 April 2011 - 08:29 PM

You're missing the point of OOP. Don't use static here. Use instance variables with non-static getter/setter methods. Static variables mean you cannot have multiple instances of your class with unique values for the fields, thus defeating the whole purpose of designing a class in general.

Also, make sure to separate your program logic from your user interface. You shouldn't be mixing user input or File I/O in your account class. Keep them separate.

As for writing to a File, make sure to flush() and close() your BufferedWriter to finish writing the data to the File.
Was This Post Helpful? 1
  • +
  • -

#3 v0rtex  Icon User is offline

  • Caffeine: db "Never Enough!"
  • member icon

Reputation: 223
  • View blog
  • Posts: 773
  • Joined: 02-June 10

Re: Need help writing to a file

Posted 01 May 2011 - 05:09 AM

You can also use:
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException {
        File reg = new File("reg.txt");
        DataOutputStream out = new DataOutputStream(new FileOutputStream(reg));
        try {
            out.writeUTF("Hey"); //obviously replace "Hey" With your functions.
        } catch (IOException e) {
            System.out.println("ERROR: Could not write to file!");
            System.exit(1);
        } finally {
            out.close();
        }
    }
}


Also try restructure your program so it conforms more with OOP standards like macosxnerd101 said.
This Java reference sheet might help you: http://www.dreaminco...ce-cheat-sheet/
Was This Post Helpful? 1
  • +
  • -

#4 codewizard  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 16
  • Joined: 20-April 11

Re: Need help writing to a file

Posted 01 May 2011 - 05:17 AM

You really must change your code a lot if you are going to use OOP, I suggest removing the static's as your instantiated object should be the only class calling them.
This might help http://www.javaworld...06-java101.html
otherwise good job :)
Was This Post Helpful? 0
  • +
  • -

#5 tam13  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 16-June 10

Re: Need help writing to a file

Posted 03 May 2011 - 10:35 PM

Thanks for all your comments so far. I've tried making changes so it's no longer static. However now in registry it isn't saving the values the user enters.
import java.util.Scanner;
import java.io.*;
/**
 * 
 * @Assignment
 * @author Tracie Marshall
 * @date January 28, 2011
 * @course ICS 211
 * 
 * A checkbook class that allows the user to store information, check the 
 * registry, make deposits, withdrawals, and check their balance.
 * 
 */
public class account {
	private String name;
	private  int checkNum;
	protected  double balance;
	private  double withdraw;
	private  double deposit;
	private double withdrawAmnt;
	private double depositAmnt;
	static double newAmnt;
	static Scanner scan = new Scanner(System.in);

	public account(){
		name = null;
		checkNum = 0;
		balance = 0;
		withdraw = 0;
		deposit = 0;
	}//End constructor

	public String getName(){
		return name;
	}//End getName

	public void setName(String newName){
		name = newName;
	}//End setName

	public int getCheckNum(){
		return checkNum;
	}//End getCheckNum

	public void setCheckNum(int newCheckNum){
		checkNum = newCheckNum;
	}//End setCheckNum

	public double getBalance(){
		System.out.println("Your balance is:" + balance);
		return balance;
	}//End getBalance

	public void setBalance(double newBalance){
		balance = newBalance;
		//System.out.println("Your balance is :" + balance);
	}//End setBalance


	public double getWithdraw(){
		return withdraw;
	}//End getWithdraw

	public void setWithdraw(double newWithdraw){
		withdraw = newWithdraw;
	}//End setWithdraw

	public double getWithdrawAmount(){
		return withdrawAmnt;
	}//End getWithdrawAmount

	public double getDepositAmount(){
		return depositAmnt;
	}//End getDepositAmount

	public double withdraw(){
		System.out.println("Please enter the amount you wish to withdraw:");
		withdraw = scan.nextDouble();
		newAmnt = balance - withdraw;
		if(newAmnt <= 0){
			System.out.println("ERROR: Insufficent funds!");
			System.exit(1);
		}//End if
		//System.out.println("Your new balance is:" + newAmnt);
		return balance - withdraw;
	}//End withdraw

	public double deposit(){
		System.out.println("Please enter the amount to deposit:");
		deposit = scan.nextInt();
		newAmnt = balance + deposit;
		System.out.println("Your new balance is:" + newAmnt);
		return balance + deposit;
	}//End deposit

	public void Registry(){
		account account = new account();
		System.out.println("Enter your name:");
		name = scan.next();
		account.setName(name);
		System.out.println("Enter your check number");
		checkNum = scan.nextInt();
		account.setCheckNum(checkNum);
		System.out.println("Enter the check amount :");
		balance = scan.nextDouble();
		account.setBalance(balance);
	}//End Registry

	public void printRegistry(){
		account account = new account();
		System.out.println("Your name is:" + account.getName());
		System.out.println("Your check number is: " + account.getCheckNum());
		System.out.println("Your balance is: " + account.getBalance());
	}//End printRegistry

	public void fileWriter() throws IOException{
		try{
			BufferedWriter out = new BufferedWriter(new FileWriter("Checkbook"));	
			out.write(getName());
			out.write((int)getCheckNum());
			out.write((int) getBalance());
			out.close();
		}
		catch(IOException e){
			System.out.println("ERROR: Could not write to file!");
			System.exit(1);
		}
	}//End fileWriter

	

	public void fileReader(){
		try{
			BufferedReader in = new BufferedReader(new FileReader ("Checkbook"));
			String str;
			while((str = in.readLine()) != null){
				System.out.println(str);
			}
			in.close();
		}catch(IOException e){
			System.out.println("ERROR: Could not read from file!");
			System.exit(1);
		}
	}//End fileReader

	public static void main(String[] args) throws IOException{
		userInterface user = new userInterface();
		user.Driver();
	}//End Main
}//End Account

/**
 * userInterfacce class allows the user access to the methods provided in checkbook.
 * @author tracieam
 *
 */
class userInterface extends account{

	//Scanner to get user input
	static Scanner scanner = new Scanner(System.in);


	public static void Driver() throws IOException{
		//Variable records the user's number entered to navigate the menu
		int option = 0 ;
		account account = new account();

		//Menu prompt
		System.out.println("Choose an option :");
		System.out.println("1. Store check information ");
		System.out.println("2. Enter into registry ");
		System.out.println("3. Make a deposit ");
		System.out.println("4. Make a withdrawal ");
		System.out.println("5. Check Balance ");
		System.out.println("6. Save Account ");
		System.out.println("7. Read Account ");
		System.out.println("8. Quit ");

		//Take in choice variable to navigate the menu
		option = scanner.nextInt();
		System.out.println("");
		String answer = null;
		//Switch controlling the menu system
		switch (option){
		//add to the registry
		case 1:
			//System.out.println("Unavailable");
			account.Registry();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//print the registry
		case 2:
			//System.out.println("Unavailable");
			account.printRegistry();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//deposit amount
		case 3:
			//System.out.println("Unavailable");
			account.deposit();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//withdraw from account
		case 4:
			//System.out.println("Unavailable");
			account.withdraw();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//get account balance
		case 5:
			//System.out.println("Unavailable");
			account.getBalance();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//write to file
		case 6:
			//System.out.println("Unavailable");
			account.fileWriter();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//Read from file
		case 7:
			//System.out.println("Unavailable");
			account.fileReader();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				Driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//Terminate the program
		case 8:
			System.out.println("Thank You for banking with us!");
			System.exit(0);
			break;
		
			//Default
		default:
			option = scanner.nextInt();
			scanner.nextLine();	
		}//End Switch
	}//End Driver
}//End UserInterface



Was This Post Helpful? 0
  • +
  • -

#6 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10668
  • View blog
  • Posts: 39,615
  • Joined: 27-December 08

Re: Need help writing to a file

Posted 04 May 2011 - 03:32 AM

Why are you creating a new account in your Registry() method? That's your problem. You are saving to a local variable, which is garbage collected when the method call ends. You should modify the instance variables instead.

Second, user input should be separate from your account. Create a class to handle this, and get/set the appropriate data in your account object(s).

Lastly, it's confusing for readers to name your class and variable name account. The compiler does fine with it, but it is not a naming convention that makes your code self-documenting.
Was This Post Helpful? 0
  • +
  • -

#7 tam13  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 18
  • Joined: 16-June 10

Re: Need help writing to a file

Posted 05 May 2011 - 09:54 PM

I took your advice and that has helped some. However my getBalance shows as 0 if I call case 4 and my file writer gives me the error message :
Exception in thread "main" java.lang.NullPointerException
at java.io.Writer.write(Writer.java:140)
at Checkbook2.fileWriter(Checkbook2.java:116)
at userInterface.driver(userInterface.java:106)
at userInterface.main(userInterface.java:151)
import java.io.*;
import java.util.Scanner;

public class Checkbook2 {
	private String name;
	private double balance;
	private int checkNum;
	private double withdraw;
	private double deposit;
	private double withdrawTotal;
	//private double depositTotal;
	Scanner scan = new Scanner(System.in);

	// Default constructor
	Checkbook2() {
		name = null;
		balance = 0;
		withdraw = 0;
		deposit = 0;
	}//End Checkbook


	// Accessor methods
	public String getName(){
		return name;
	}//End getName
	
	private int getCheckNum() {
		return checkNum;
	}//End getCheckNum

	public double getBalance(){
		System.out.println("Your balance is : " + balance);
		return balance;
	}//End getBalance

	public double getWithdraw(){
		return withdraw;
	}//End getWithdraw

	public double getDeposit(){
		return deposit;
	}//End getDeposit

	public double getWithdrawTotal() {
		return withdrawTotal;
	}//End getWithdrawTotal

	// Mutator methods
	public void setName(String newName){
		name = newName;
	}//End setName

	public void setCheckNum(int newCheckNum){
		checkNum = newCheckNum;
	}//End setCheckNum
	
	public void setBalance(double newBalance){
		balance = newBalance;
	}//End setBalance

	public void setWithdraw(double newWithdraw){
		withdraw = newWithdraw;
	}//End setWithdraw

	public void setDeposit(double newDeposit){
		deposit = newDeposit;
	}//End setDeposit


	public double withdraw() {
		return balance - withdraw;
	}//End Withdraw
	
	public double withdraw(double withdraw){
		return balance - withdraw;
	}

	public double withdrawTotal(){
		withdrawTotal = balance - withdraw;
		return withdrawTotal;
	}
	public double deposit(){
		return withdrawTotal + deposit;
	}//End Deposit
	
	public double deposit(double deposit){
		return withdrawTotal + deposit;
	}

	// void method to display the account
	public void Registry(String name, int checkNum, double balance, double withdraw, double deposit) {
		Checkbook2 check = new Checkbook2();
		check.setName(name);
		check.setCheckNum(checkNum);
		check.setBalance(balance);
		check.setWithdraw(withdraw);
		check.setDeposit(deposit);

		// Displaying using the get methods
		System.out.println("Your name is:" + check.getName());
		System.out.println("Your check number is : " + check.getCheckNum());
		check.getBalance();
		System.out.println("Amount of withdrawal is:" + check.getWithdraw());
		System.out.println("The Balance after withdrawal is:" + check.withdrawTotal());
		System.out.println("Amount of deposit is:" + check.getDeposit());
		System.out.println("The balance after deposit is : " + check.deposit());
		
	}//End Registry

	public void fileWriter(){
		//Checkbook2 write = new Checkbook2();
		//System.out.println("Unavailable");
		try{
			BufferedWriter out = new BufferedWriter(new FileWriter("Checkbook"));	
			out.write(getName());
			out.write(getCheckNum());
			out.write((int) getBalance());
			out.close();
		}
		catch(IOException e){
			System.out.println("ERROR: Could not write to file!");
			System.exit(1);
		}
	}

	public void fileReader(){
		//System.out.println("Unavailable");
		try{
			BufferedReader in = new BufferedReader(new FileReader ("Checkbook"));
			String str;
			while((str = in.readLine()) != null){
				System.out.println(str);
			}
			in.close();
		}catch(IOException e){
			System.out.println("ERROR: Could not read from file!");
			System.exit(1);
		}
	}
	
	public static void main (String[] args){
		//Checkbook2 checking = new Checkbook2();
	}
}//End Main




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

public class userInterface  extends Checkbook2{
	public void driver () throws IOException{
		//Variable records the user's number entered to navigate the menu
		int option = 0 ;
		Scanner scanner = new Scanner(System.in);
		//Menu prompt
		System.out.println("Choose an option :");
		System.out.println("1. Store check information ");
		System.out.println("2. Make a deposit ");
		System.out.println("3. Make a withdrawal ");
		System.out.println("4. Check Balance ");
		System.out.println("5. Save Account ");
		System.out.println("6. Read Account ");
		System.out.println("7. Quit ");

		//Take in choice variable to navigate the menu
		option = scanner.nextInt();
		System.out.println("");
		String answer = null;
		//Switch controlling the menu system
		switch (option){
		//add to the registry
		case 1:
			//System.out.println("Unavailable");
			System.out.println("Please enter your name");
			String name = scan.next();
			System.out.println("Please enter your check number");
			int checkNum = scan.nextInt();
			System.out.println("Balance");
			double balance = scan.nextDouble();
			System.out.println("Withdraw");
			double withdraw = scan.nextDouble();
			System.out.println("Deposit");
			double deposit = scan.nextDouble();
			Registry(name,checkNum, balance, withdraw, deposit);
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//makes a deposit
		case 2:
			//System.out.println("Unavailable");
			System.out.println("Enter the amount you wish to deposit");
			deposit = scan.nextDouble();
			deposit(deposit);
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//withdraw from account
		case 3:
			//System.out.println("Unavailable");
			System.out.println("Enter the amount you wish to withdraw : ");
			withdraw = scan.nextDouble();
			withdraw(withdraw);
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//get account balance
		case 4:
			//System.out.println("Unavailable");
			System.out.println("Your balance is : " + getBalance());
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//write to file
		case 5:
			//System.out.println("Unavailable");
			fileWriter();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//Read from file
		case 6:
			//System.out.println("Unavailable");
			fileReader();
			System.out.println("Would you like to make another transaction ? Y/N");
			answer = scanner.next();
			if(answer.equalsIgnoreCase("y")|| answer.equalsIgnoreCase("yes")){
				driver();
			}else if(answer.equalsIgnoreCase("n")|| answer.equalsIgnoreCase("no")){
				System.out.println("Goodbye!");
				System.exit(0);
			}else{
				System.out.println("Invalid Selection!");
				System.exit(1);
			}
			break;
			//Terminate the program
		case 7:
			System.out.println("Thank You for banking with us!");
			System.exit(0);
			break;

			//Default
		default:
			option = scanner.nextInt();
			scanner.nextLine();	
		}//End Switch
	}

	public static void main (String [] args) {
		userInterface ui = new userInterface();
		try {
			ui.driver();
		} catch (IOException e){
			// throws IOException
			e.printStackTrace();
		}

	}
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1