473,626 Members | 3,420 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reading and Writing a Text File???

10 New Member
Help! I need to write a program that reads a text file with numbers and sums up each line of numbers. Then write a part of the program that outputs the text to another file. How do I do this?
Here's what the data file looks like:
1 2
2 3
3 4
4 5
5 6
Here is the code I have:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.PrintWriter;
  4.  
  5. public class SumFile 
  6.   {
  7.   public static void main( String[] args ) throws Exception 
  8.   {
  9.  
  10.     File f = new File("data.txt");
  11.  
  12.     Scanner input = new Scanner(f);
  13.  
  14.     String name;
  15.     int number;
  16.     int sum;
  17.  
  18.  
  19.     while ( input.hasNext() )
  20.     {
  21.       number = input.nextInt();
  22.       number = input.nextInt();
  23.       number = input.nextInt();
  24.       number = input.nextInt();
  25.       number = input.nextInt();
  26.       number = input.nextInt();
  27.  
  28.       sum= number + number;
  29.  
  30.      System.out.printf("The file sum is " + sum);
  31.     }
  32.     File g = new File("result.txt");
  33.  
  34.     PrintWriter output = new PrintWriter(g);
  35.     output.println
  36.  
  37.  
  38.     input;.close();
  39.   }
  40. }
  41.  
Mar 20 '08 #1
2 2514
sukatoa
539 Contributor
Help! I need to write a program that reads a text file with numbers and sums up each line of numbers. Then write a part of the program that outputs the text to another file. How do I do this?
Here's what the data file looks like:
1 2
2 3
3 4
4 5
5 6
Here is the code I have:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.PrintWriter;
  4.  
  5. public class SumFile 
  6.   {
  7.   public static void main( String[] args ) throws Exception 
  8.   {
  9.  
  10.     File f = new File("data.txt");
  11.  
  12.     Scanner input = new Scanner(f);
  13.  
  14.     String name;
  15.     int number;
  16.     int sum;
  17.  
  18.  
  19.     while ( input.hasNext() )
  20.     {
  21.       number = input.nextInt();
  22.       number = input.nextInt();
  23.       number = input.nextInt();
  24.       number = input.nextInt();
  25.       number = input.nextInt();
  26.       number = input.nextInt();
  27.  
  28.       sum= number + number;
  29.  
  30.      System.out.printf("The file sum is " + sum);
  31.     }
  32.     File g = new File("result.txt");
  33.  
  34.     PrintWriter output = new PrintWriter(g);
  35.     output.println
  36.  
  37.  
  38.     input;.close();
  39.   }
  40. }
  41.  
You can just use Formatter for writing file....(Useful for debugging)
And Scanner for reading...

Your implementation is confusing....
When you read the data inside the file, you must store them in different variable...

You are just simply storing the values in a variable only...

For example,

1 2
2 3
3 4 -> the node is on this now....Assuming ....

The number variable gets the 4 (last value before EOF)

And you are just summing the same value 4 + 4 = 8
You cannot say 3 + 4 = 7 Base on your code posted....

Maybe like this:

Expand|Select|Wrap|Line Numbers
  1. datatype sum set zero
  2.  
  3. while( StillHasValueAtNextPointing ) {
  4.        num1 = firstvalueCurrentLine
  5.        num2 = secondValueCurrentLine
  6.        sum += ( num1 + num2 )
  7. }
  8.  
  9. Save the sum into another file....

Correct me if im wrong,
Sukatoa
Mar 20 '08 #2
satch
23 New Member
Help! I need to write a program that reads a text file with numbers and sums up each line of numbers. Then write a part of the program that outputs the text to another file. How do I do this?
Here's what the data file looks like:
1 2
2 3
3 4
4 5
5 6
Here is the code I have:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Scanner;
  2. import java.io.File;
  3. import java.io.PrintWriter;
  4.  
  5. public class SumFile 
  6.   {
  7.   public static void main( String[] args ) throws Exception 
  8.   {
  9.  
  10.     File f = new File("data.txt");
  11.  
  12.     Scanner input = new Scanner(f);
  13.  
  14.     String name;
  15.     int number;
  16.     int sum;
  17.  
  18.  
  19.     while ( input.hasNext() )
  20.     {
  21.       number = input.nextInt();
  22.       number = input.nextInt();
  23.       number = input.nextInt();
  24.       number = input.nextInt();
  25.       number = input.nextInt();
  26.       number = input.nextInt();
  27.  
  28.       sum= number + number;
  29.  
  30.      System.out.printf("The file sum is " + sum);
  31.     }
  32.     File g = new File("result.txt");
  33.  
  34.     PrintWriter output = new PrintWriter(g);
  35.     output.println
  36.  
  37.  
  38.     input;.close();
  39.   }
  40. }
  41.  
You should realize that in lines 22 to 26 of your code you are replacing the value stored in variable 'number' with a new value. Now this does not make sense when you want to use every value that you read from the file.

Every time you assign a new value to the variable 'number' you loose the previous value, so you better use it before overwriting it. And if you want to use two value simultaneously in some statement then you should store them in two different variables.
Mar 20 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

6
1775
by: Kevin T. Ryan | last post by:
Hi All - I'm not sure, but I'm wondering if this is a bug, or maybe (more likely) I'm misunderstanding something...see below: >>> f = open('testfile', 'w') >>> f.write('kevin\n') >>> f.write('dan\n') >>> f.write('pat\n') >>> f.close()
4
6405
by: john smith | last post by:
Hi, I have a file format that is going to contain some parts in ascii, and some parts with raw binary data. Should I open this file with ios::bin or no? For example: filename: a.bin number of points = 123 @@@begin data@@@ gibberish follows.....
4
9823
by: Oliver Knoll | last post by:
According to my ANSI book, tmpfile() creates a file with wb+ mode (that is just writing, right?). How would one reopen it for reading? I got the following (which works): FILE *tmpFile = tmpfile(); /* write into tmpFile */ ...
2
3062
by: Jeevan | last post by:
Hi, I have an array of data (which I am getting from a socket connection). I am working on a program which acts on this data but the program is written to work on data from a file (not from an array). I cannot change anything in the program but can add some features by which I can convert this array of data into a file. The easiest thing would be to write the data into a file (in hard disk) and use it. But I will be working on thousands...
1
2011
by: Need Helps | last post by:
Hello. I'm writing an application that writes to a file a month, day, year, number of comments, then some strings for the comments. So the format for each record would look like: mdyn"comment~""comment~"\n Now, I wrote some code to read these records, and it works perfectly for every date I've tried it on, except when the day is 26. I tried saving a record for 6/26/2004 and 7/26/2004 and it read it in as the day, year, and number of...
9
2753
by: Alex Buell | last post by:
I have a small text file which consist of the following data: ]] And the code I've written is as follows: ]] The trouble is, I can't work out why it goes into an infinite loop reading the information from the text file! Can anyone enlighten me as to what I am doing wrong?
6
5259
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
42
4844
by: psbasha | last post by:
Hi, Is it necessary in Python to close the File after reading or writing the data to file?.While refering to Python material ,I saw some where mentioning that no need to close the file.Correct me if I am wrong. If possible could anybody help me with sample code for reading and writing a simple text file.I have seen there are many ways to read /write the data in Python.But I want to use the effective way of reading or writing the data...
2
4553
by: Clive Green | last post by:
Hello peeps, I am using PHP 5.2.2 together with MP3_Id (a PEAR module for reading and writing MP3 tags). I have been using PHP on the command line (Mac OS X Unix shell, to be precise), and am getting on more or less OK. So far, I have managed to parse my tab-delimited .txt file properly into an array, and then use this array to update the tags on a bunch of MP3 audio files. Nice.
4
3212
by: pbj2009 | last post by:
Hello all: I'm pretty stumped on this one. I'm not looking for Code, I'm just trying to figure out the best way to start this since I am new to reading and writing from files. I can't figure out what section (main/btnOpen/frmExceptionsLoad) to put the code and all tutorials have either reading from or writing to and I am confused about putting it together along with the calculations of course. I have to write a program that when I click a...
0
8268
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8202
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8707
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8641
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8510
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6125
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5575
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4202
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1512
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.