Basically, I was wondering how I could read a text file (Transactions.txt) which will have one
number per line(ex. 2000 on one line, 25 on another). This number is either a deposit or a withdrawal to a checking account. The program should read the Transactions.txt , then write the deposits (positive numbers) to an output file named Deposits.txt and the withdrawals (negative numbers) to an output file named Withdrawals.txt. Each number should be displayed on the screen as it is read from the file. I have figured out how to read the Transaction file and display the first line, but I'm not sure from there.

public static void main(String[] args) throws IOException
	{
			
		//Open the file.
		File file = new File("Transactions.txt");
		Scanner inputFile = new Scanner(file);
		
		//Read the first line from the file.
		String line = inputFile.nextLine();
		
		//Display the line.
		System.out.println("The first line in the file is:");
		System.out.println(line);
						
		//Close the file.
		inputFile.close();

Recommended Answers

All 7 Replies

What does that do?

What does that do?

That isn't a helpful response. "What does that do?" could mean several things, as could the word "that". Do you not understand why masijade suggested two FileOutputStreams? Do you not understand why he suggested to use parseInt? Do you not know how to use them? Etc. etc. Don't make us guess.

What does that do?

I gave you alink to the API docs and the IO Tutorial. Look it up.

I understand what your saying, and I know how to open an output file and use a Scanner object to insert text into it. I am not sure how to open a text file and from that text file extract numbers to go into an output file.

Thanks for the help, I figured it out. Take a look and let me know if this is what you were trying to explain.

import java.util.Scanner;				//Needed for Scanner class
import java.io.*;							//Needed for File I/O classes

public class Transactions
{
	public static void main(String[] args) throws IOException
	{
		double num;		
		
		//Create objects
		File file = new File("Transactions.txt");
		Scanner inputFile = new Scanner(file);
		PrintWriter outputFile = new PrintWriter("Withdrawals.txt");
		PrintWriter outputFile1 = new PrintWriter("Deposits.txt");		
	
		//Get all values and display.
		while (inputFile.hasNext())
		{
			num = inputFile.nextDouble();			//Reads lines from "Transactions.txt"
			
				if (num > 0)							
					{
						outputFile1.println(num);	//Prints to Deposits.txt
	  				}
				else
					{
						outputFile.println(num);	//Prints to Withdrawals.txt
					}
						System.out.println(num);	//Displays the lines.
					}								
		
		//Close the files.
		inputFile.close();
		outputFile.close();
		outputFile1.close();
	
	}
}

Yes. Congratulations.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.