I'm having all sorts of problems getting this program to work. I think I know what's wrong with it, but I don't know how to fix the problem.

The program is supposed to read a text file that contains information like below....

1 99
2 88
3 77
4 66
5 55
1 10
2 35
5 50
3 60

It supposed to add up the numbers on the right, corresponding with the numbers on the left and write that information to a file. For example there are 105 "5"s and 123 "2"s.

So the new file should look like this

1 109
2 123
3 137
4 66
5 105

I have to do the writing with a Method, and that method has to be accessed 5 times....

I've been working on this little program for 2 days now, and I really don't think the teacher explained this.

The problem is...when I open my newly created text file. All I see is the last one "5 105"

I'm guessing this is because each time the detail line method runs, it writes over the last entry (or creates a new txt file over the last one). I thought I could get read of this problem by moving the creation point of my outputfile (summaryReport) to my main, but then my method has all sorts of problems..as it doesn't recognize what summaryReport is.

Can anyone point me in the right direction.

public class SpacelySprockets
{

	public static void main(String[] args) //Main Program
	{  //Start Main


		int partNumber=0;
		int quantity=0;
		int part1Total=0;
		int part2Total=0;
		int part3Total=0;
		int part4Total=0;
		int part5Total=0;

		Keyboard kbd;
		kbd = new Keyboard ();

		InputFile sprockets;
		sprockets = new InputFile ("H:\\MaxSync\\School\\SLCC\\CIS 1030\\Spacely Sprockets\\sprockets.txt");

		OutputFile summaryReport;
		summaryReport = new OutputFile ("H:\\MaxSync\\School\\SLCC\\CIS 1030\\Spacely Sprockets\\summaryReport.txt");

		while (!sprockets.eof())
		{   //Start Loop

			partNumber=sprockets.readInt ();
			quantity=sprockets.readInt ();


			switch (partNumber)
			{
				case 1:		part1Total = part1Total + quantity;
							break;
				case 2:		part2Total = part2Total + quantity;
							break;
				case 3:		part3Total = part3Total + quantity;
							break;
				case 4:		part4Total = part4Total + quantity;
							break;
				case 5:		part5Total = part5Total + quantity;
							break;
				default:	System.out.println ("The file has unknown part numbers ltstd");
			}


		}   //End Loop

		detailLine (part1Total, 1);
		detailLine (part2Total, 2);
		detailLine (part3Total, 3);
		detailLine (part4Total, 4);
		detailLine (part5Total, 5);
		


	}  //End Main

	public static void detailLine (int partTotal, int partNumber)
	{
		OutputFile summaryReport;
		summaryReport = new OutputFile ("H:\\MaxSync\\School\\SLCC\\CIS 1030\\Spacely Sprockets\\summaryReport.txt");

		summaryReport.writeString (partNumber+"     "+partTotal);
		summaryReport.writeEOL();
                                summaryReport.close();

	}


} //End Class

You are correct - you're overwriting the file on each invocation of detailLine. To fix that, you could make the output file a class-level variable or pass a reference to it as a parameter. Either way, do not open or close the file in that method - just write the data. Close it after all of the data has been written.

You are correct - you're overwriting the file on each invocation of detailLine. To fix that, you could make the output file a class-level variable or pass a reference to it as a parameter. Either way, do not open or close the file in that method - just write the data. Close it after all of the data has been written.

How do you make the output file a class level variable and get the method to recognize the file when your only writing lines?

thanks
jeff

class level variables can be accessed by all methods.

OutputFile summaryReport;
try making this a class-level variable.


summaryReport = new OutputFile ("H:\\MaxSync\\School\\SLCC\\CIS 1030\\Spacely Sprockets\\summaryReport.txt");
umm.. i think u can put this in the main method,, not sure thou!!

Yes, you just move it up as indicated above. It would need to be declared static since the method that is writing to it is static and it is accessed in main. (That is not really a good way to code things, but the original poster decided to use everything statically)

When I put it in main the method just below the initialzation of the variables the detailed line method gives the error cannot find symbol. There appears to be a need to reference or call the file in the detailedline method. What would be a better way.

OutputFile summaryReport;
summaryReport = new OutputFile ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\summaryReport.txt");

I also have the file closing after the 5 detailed line paramaters are sent. Only detail line info is written.


This class is has a poorly written professor book and the only way to get through is pain. I bought Heads up Java and am working through the chapters as fast as possible prior to term final but the sections to make this understandable are in the 400 -550 page range.

Thanks for your responses

jeff

Do you have a class called OutputFile? The code he posted was using some wrapper class called OutputFile - it's not a standard API class.

this is the output file. We are supposed to use this written by the prof and make it work. instead of learning how to read a file onour own we have this and I about 300 pages away from this point in head up java. He condensed everything to read the file into this and it was even bugged when I got it.

[


import java.io.*;
import java.text.DecimalFormat;
public class OutputFile extends Keyboard
{
private String fn;
private OutputStreamWriter out;


public OutputFile(String fn)
{
try
{
out = new OutputStreamWriter(new FileOutputStream(fn));
}    catch( Exception e )
{
System.out.println( "Can't open output file '" + fn + "'" );
Keyboard standardInput = new Keyboard();
System.out.print( "Enter new file name or press enter to end program: " );
fn = standardInput.readLine( );
if( fn.length() == 0 )
System.exit( 1 );
}
}


public void close()
{
try
{
out.close();
}catch (IOException e){error("close");}
}



public void writeEOL()
{
try
{
out.write("\n");
}catch(IOException e){error("writeInt");}
}



public void writeInt(int i)
{
try
{
String s = "";
out.write(s.valueOf(i) + " ");
}catch(IOException e){error("writeInt");}
}



public void writeDouble(double d)
{
try
{
DecimalFormat df = new DecimalFormat("0.0 ");
out.write(df.format(d));
}catch(IOException e){error("writeDouble");}
}


public void writeString(String s)
{
try
{
out.write('"' + s + '"' + " ");
}catch(IOException e){error("writeString");}
}


public void writeWord(String s)
{
try
{
out.write( s + " ");
}catch(IOException e){error("writeWord");}
}


public void writeChar(char c)
{
try
{
out.write(c + " ");
}catch(IOException e){error("writeString");}
}
}


}

Edited 3 Years Ago by happygeek: fixed formatting

tried to post better

[import java.io.*;
import java.text.DecimalFormat;
public class OutputFile extends Keyboard
{
private String fn;
private OutputStreamWriter out;


public OutputFile(String fn)
{
try
{
out = new OutputStreamWriter(new FileOutputStream(fn));
}    catch( Exception e )
{
System.out.println( "Can't open output file '" + fn + "'" );
Keyboard standardInput = new Keyboard();
System.out.print( "Enter new file name or press enter to end program: " );
fn = standardInput.readLine( );
if( fn.length() == 0 )
System.exit( 1 );
}
}


public void close()
{
try
{
out.close();
}catch (IOException e){error("close");}
}



public void writeEOL()
{
try
{
out.write("\n");
}catch(IOException e){error("writeInt");}
}



public void writeInt(int i)
{
try
{
String s = "";
out.write(s.valueOf(i) + " ");
}catch(IOException e){error("writeInt");}
}



public void writeDouble(double d)
{
try
{
DecimalFormat df = new DecimalFormat("0.0 ");
out.write(df.format(d));
}catch(IOException e){error("writeDouble");}
}


public void writeString(String s)
{
try
{
out.write('"' + s + '"' + " ");
}catch(IOException e){error("writeString");}
}


public void writeWord(String s)
{
try
{
out.write( s + " ");
}catch(IOException e){error("writeWord");}
}


public void writeChar(char c)
{
try
{
out.write(c + " ");
}catch(IOException e){error("writeString");}
}
}
]

Edited 3 Years Ago by happygeek: fixed formatting

When I put it in main the method just below the initialzation of the variables the detailed line method gives the error cannot find symbol. There appears to be a need to reference or call the file in the detailedline method. What would be a better way.

I'm not following your description of the problem. If you would post your code (use the [ code] tags around it please), it would certainly help.

there we go. What is the parameter or way to get the detailed line method to recognize the outputfile summary report.

thanks


jeff

import java.io.*;
import java.text.DecimalFormat;
public class OutputFile extends Keyboard
{
    private String fn;
    private OutputStreamWriter out;
    
    public OutputFile(String fn)
    {
        try
        {
           out = new OutputStreamWriter(new FileOutputStream(fn));
        }    catch( Exception e ) 
        {
          System.out.println( "Can't open output file '" + fn + "'" );
          Keyboard standardInput = new Keyboard();
          System.out.print( "Enter new file name or press enter to end program: " );
          fn = standardInput.readLine( );
          if( fn.length() == 0 )
              System.exit( 1 );
        }
    }
    
    public void close()
    {
        try
        {
            out.close();
        }catch (IOException e){error("close");}
    }
    
     
    public void writeEOL()
    {
        try
        {
            out.write("\n");
        }catch(IOException e){error("writeInt");}
    }
    
    
    public void writeInt(int i)
    {
       try
       {
           String s = "";
           out.write(s.valueOf(i) + " ");
       }catch(IOException e){error("writeInt");}
    }
    
    
    public void writeDouble(double d)
    {
       try
       {
        DecimalFormat df = new DecimalFormat("0.0 ");
        out.write(df.format(d));
       }catch(IOException e){error("writeDouble");}
    }
    
    public void writeString(String s)
    {
       try
       {
        out.write('"' + s + '"' + " ");
       }catch(IOException e){error("writeString");}
    }
    
    public void writeWord(String s)
    {
       try
       {
        out.write( s + " ");
       }catch(IOException e){error("writeWord");}
    }
    
    public void writeChar(char c)
    {
       try
       {
        out.write(c + " ");
       }catch(IOException e){error("writeString");}
    }
}

there we go. What is the parameter or way to get the detailed line method to recognize the outputfile summary report.

Ok, that is not the code I was referring to. You posted the OutputFile class, but your questions relate to how you are using it in another program. That is the code I was asking about, because your question is not clear.

The code is similar to the first post. I have tried many ways to get the output file to jump down to the detail line method and cannot seem to figure it out. Is this what your looking for?

jeff

public class SpacelySprockets
{

 	//OutputFile summaryReport;
 	//summaryReport = new OutputFile ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\summaryReport.txt");


	public static void main(String[] args)
	{
		int partNumber=0;
		int quantity=0;
		int part1Total=0;
		int part2Total=0;
		int part3Total=0;
		int part4Total=0;
		int part5Total=0;
		int closeLoop=0;

		OutputFile summaryReport;
		summaryReport = new OutputFile ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\summaryReport.txt");


		Keyboard kbd;
		kbd = new Keyboard ();

		System.out.println ("Reading the prior days sales and creating output file");

		InputFile sprockets;
		sprockets = new InputFile ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\sprockets1.txt");

		while (!sprockets.eof())
		{   //Start Loop

			partNumber=sprockets.readInt ();
			quantity=sprockets.readInt ();




			switch (partNumber)
			{
				case 1:		part1Total = part1Total + quantity;
							break;
				case 2:		part2Total = part2Total + quantity;
							break;
				case 3:		part3Total = part3Total + quantity;
							break;
				case 4:		part4Total = part4Total + quantity;
							break;
				case 5:		part5Total = part5Total + quantity;
							break;

				default:	System.out.println ("Bad sprocket number");
			}

			//System.out.println (partNumber);    	//test to check for partNumber file read
			//System.out.println (quantity);  		//test to check for quantity file read



		}

		System.out.println ("File has been successfully created");



		detailLine (1, part1Total, 1);
		detailLine (2, part2Total, 0);
		detailLine (3, part3Total, 0);
		detailLine (4, part4Total, 0);
		detailLine (5, part5Total, 1);


		//summaryReport.close();

	}

	public static void detailLine (int partNumber, int partTotal, int closeLoop)

	{


				//OutputFile summaryReport;
				//summaryReport = new OutputFile ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\summaryReport.txt");

				//File.Open ("G:\\CIS 1030\\Spacley\\SpacelySprockets\\summaryReport.txt");

				if (closeLoop == 0)

				{

				summaryReport.writeInt (partNumber);
				summaryReport.writeWord ("                    ");
				summaryReport.writeInt (partTotal);
				summaryReport.writeEOL();
				System.out.println (partNumber);
				System.out.println (partTotal);


				}

				else {summaryReport.close();}

				//summaryReport.close();
	}


} //End Class

Yes, that is the code I was asking about, but you have commented out all of the relevant initializations.

The static class method will only be able to access static class variables or a parameter that is passed to it. So you can either declare the OutputFile variable static at the class level and initialize it in main(), or you can alter the method signature to take that OutputFile as a parameter and use it within the method.

I would actually recommend altering the method signature and passing the OutputFile as a parameter.

Edit: Also, you don't need to close the file in that method based on "closeLoop" - just let the method write the information to the file that is passed to the method. The main() program can close the file after you are finished with it.

This article has been dead for over six months. Start a new discussion instead.