Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Writing to file in java - problem

Options
  • 20-02-2008 2:07am
    #1
    Registered Users Posts: 7,155 ✭✭✭


    Having a problem with the above.

    When i write to the file it over-writes what i've previously written in the same run instance.

    I appreciate any help you can give.

    Heres my code:
    import java.io.*;
    
    import javax.swing.JOptionPane;
    
    
    //17/12/07
    
    public class Tower 
    {
    	public static void main( String[] args ) 
    	{
    		int towerSelect = 0,
    			destination = 0,
    			tempBlock = 0,
    			tempLocation = 0,
    		    numBlocks = 0,
    		    testCompleted = 0,
    			completedCheck = 0,
    			mostSignificant = 0,
    			addressKey = 0,
    			moveCount = 0;
    		String tempStr;
    		String addressString;
    		boolean check = false;
    		boolean towerCheck = false;
    		boolean completed = false;
    		boolean nonZero = false;
    		boolean moving = false;
    		
    		while (check == false)
    		{
    			//Selecting the number of blocks to play with
    			tempStr = JOptionPane.showInputDialog("Please enter number of blocks (3-8)");
    			numBlocks = Integer.parseInt(tempStr);
    			
    			if ((numBlocks>=3)&&(numBlocks<=8))
    			{
    				check = true;	
    			}
    			else
    			{
    				JOptionPane.showMessageDialog(null, "Incorrect selection");
    			}
    		}
    		//making an array using the previous selection
    		int[][] game = new int[numBlocks][3] ;
    		
    		//Setting up first tower 
    		for ( int i = 0; i < numBlocks; i++ )
    		{
    			game[i][0]= (i + 1);
    			completedCheck = completedCheck + (i+1);
    		}
    		
    		while(completed == false)
    		{
    			//Printing the tower
    			for ( int i = 0; i < numBlocks; i++ )
    			{
    				for ( int j = 0; j < 3; j++ )
    				{
    					System.out.print(" ");
    					System.out.print( game[i][j] );
    					System.out.print(" ");
    				}
    				System.out.println();
    			}
    			System.out.println("---------");
    			
    			//Checking for most significant other tower
    			//most significant based on what has largest base number
    			
    			mostSignificant = 0;
    			addressKey = 0;
    			
    			if ( game[2][1] > game[2][0])
    			{
    				mostSignificant = 1;
    			}
    			System.out.println("MS = " + mostSignificant);
    			
    			//address key code
    			
    			//target-pole code
    			
    			addressKey = addressKey + (game[0][2])*100000;
    			addressKey = addressKey + (game[1][2])*10000;
    			addressKey = addressKey + (game[2][2])*1000;
    			
    			//MSO-pole code
    			
    			addressKey = addressKey + (game[0][mostSignificant])*100;
    			addressKey = addressKey + (game[1][mostSignificant])*10;
    			addressKey = addressKey + (game[2][mostSignificant]);
    			
    			//System.out.println("Address key = " + addressKey);
    			//System.out.println("");
    			
    	[COLOR="Red"]		// WORK IN PROGRESS!!!!
    			try
    			{
    				BufferedWriter out = new BufferedWriter (new FileWriter("test.txt"));
    				
    				addressString = String.valueOf(addressKey);
    				out.write(addressString);
    				out.newLine();
    				out.close();
    			} catch (Exception e){
    				
    			}[/COLOR]
    			
    			//checking for completion
    			testCompleted=0;
    			for ( int i = 0; i < numBlocks; i++ )
    			{
    				testCompleted = game[i][2]+ testCompleted;
    			}
    			if (testCompleted==completedCheck)
    			{
    				JOptionPane.showMessageDialog(null, "Completed. It took "+moveCount+" moves");
    				completed=true;
    			}
    			
    			//Main game handling
    			if (completed==false)
    			{
    				moving = false;
    				while(moving == false)
    				{
    					towerCheck=false;
    					while(towerCheck == false)
    					{
    						//selecting source tower
    						tempStr = JOptionPane.showInputDialog("Please select tower (1,2 or 3)");
    						towerSelect = Integer.parseInt(tempStr);
    						if ((towerSelect>=1)&&(towerSelect<=3))//making sure selection is in bounds
    						{
    							for ( int i = numBlocks; i > 0; i-- )
    							{
    								if (game[i-1][(towerSelect-1)] != 0)
    								{
    									
    									tempLocation = i-1;
    									tempBlock = (game[i-1][(towerSelect-1)]);
    									towerCheck = true;
    								}
    							}
    							if (towerCheck==false)
    							{
    								JOptionPane.showMessageDialog(null, "there is no blocks on this tower");
    							}
    						}
    						else
    						{
    							JOptionPane.showMessageDialog(null, "Invalid selection");
    						}
    					}
    					tempStr = JOptionPane.showInputDialog("Please select destination (1,2 or 3)");
    					destination = Integer.parseInt(tempStr);
    					if ((destination>=1)&&(destination<=3))
    					{
    						if (towerSelect!=destination)
    						{
    							nonZero=false;
    							for ( int i = 0; i < numBlocks; i++ )
    							{
    								if (game[i][(destination-1)] != 0)
    								{
    									nonZero=true;
    									if ((game[i][(destination-1)])>tempBlock)
    									{
    										(game[i-1][(destination-1)])=tempBlock;
    										(game[tempLocation][towerSelect-1])=0;
    										moving=true;
    									}
    									else
    									{
    										JOptionPane.showMessageDialog(null, "Selected block is bigger than destination block");
    									}
    									i=numBlocks;
    								}
    								
    							}
    							if (nonZero == false)
    							{
    								game[numBlocks-1][destination-1]=tempBlock;
    								game[tempLocation][towerSelect-1]=0;
    								moving=true;
    							}
    						}
    						else
    						{
    							//Exiting the loop if destination and select are the same
    							moving=true;
    						}
    										
    					}
    				}
    				
    				moveCount = moveCount + 1;
    			}
    		}
    			
    		
    		
    	System.exit(0);	
    	}
    	
    	
    }
    
    


Comments

  • Closed Accounts Posts: 1,444 ✭✭✭Cantab.


    Oh deary me.

    Ever heard of google?

    What error are you getting?

    Btw, here's the first result google gave me when I typed in "Java write to file"
    import java.io.*;
    class FileWrite 
    {
      public static void main(String args[])
      {
        try
        {
           // Create file 
           FileWriter fstream = new FileWriter("out.txt");
           BufferedWriter out = new BufferedWriter(fstream);
           out.write("Hello Java");
           //Close the output stream
           out.close();
        }
        catch (Exception e)
        {
           //Catch exception if any
           System.err.println("Error: " + e.getMessage());
        }
      }
    }
    


  • Registered Users Posts: 7,155 ✭✭✭witnessmenow


    Google? What is that:rolleyes:

    I appreciate you making the effort to reply but did you even read my post? I said what error i was getting.

    I also posted up my code , and i highlighted the part in red that applies, which is basically exactly the same as what you posted.


  • Closed Accounts Posts: 1,444 ✭✭✭Cantab.


    Google? What is that:rolleyes:

    I appreciate you making the effort to reply but did you even read my post? I said what error i was getting.

    I also posted up my code , and i highlighted the part in red that applies, which is basically exactly the same as what you posted.

    Mate, post the output error from the compiler and I'll have a look at it for ya...

    The bit with the line numbers in it like...

    Code looks very messy and incosistent (with regard to tabs/spaces/new lines etc.) Are you using Eclipse or a text editor or what?

    Also, the code goes very far over to the right! You need to cull some of that code and wrap it up in functions!


  • Registered Users Posts: 413 ✭✭ianhobo


    while(completed == false)
    {
       .........
         // WORK IN PROGRESS!!!!
         try
         {
    	BufferedWriter out = new BufferedWriter (new FileWriter("test.txt"));
    	addressString = String.valueOf(addressKey);
    	out.write(addressString);
    	out.newLine();
    	out.close();
          }
          catch (Exception e)
          {
    	
          }
    }
    

    You problem appears to be in this bit ^
    This is all contained within a while loop.

    Through one iteration of the while loop, you create a new file called test.txt, write out some data and close the file.

    If you are not "completed", your while loop runs again where you.... create a new file called test.txt, write out some data and close the file.

    So you overwrite the old data everytime.

    You have two solutions,
    1. Create the file outside (before) the while loop, and close the file when completed == true

    2. Use the append flag in FileWriter class call. Currently you tell FileWriter to create a new file everytime, so if it already exists, bye bye existing data, it all gets over written. FileWriter can be overloaded with an append flag. This option wil probably mean the least amount of changes to your code.

    From the J2SE manual
    public FileWriter(String fileName, boolean append)
    throws IOException

    Another thing to note, is that your code probably has too many nested conditional statements (The main game handling section). Generally if you have to go further than 3 or 4 nested conditional statements, there is something wrong with the way you would be trying to implement your solution (not always of course! :) ) See if you can condense the logic in the section, if will probably be of benefit in the long run anyway


  • Registered Users Posts: 7,468 ✭✭✭Evil Phil


    The OP followed the rules as outlined in the Forum Charter, if anyone has a problem with a post then please use the report post function.

    Btw, it helps if you actually read the post before complaining about it.


  • Advertisement
  • Registered Users Posts: 7,155 ✭✭✭witnessmenow


    thanks for your help, didn't spot/kop that at all! as for the nested loops/statements its too late to turn back now!:D


  • Closed Accounts Posts: 9 deeringc


    thanks for your help, didn't spot/kop that at all! as for the nested loops/statements its too late to turn back now!:D

    Thats not true, refactoring is definitely worthwhile! You learn how to write it right first time by going back into your code an improving it!


  • Registered Users Posts: 11,980 ✭✭✭✭Giblet


    Always refactor, then you never have to look back (until you refactor again, ya see)


  • Registered Users Posts: 21,264 ✭✭✭✭Hobbes


    addressString = String.valueOf(addressKey);

    You can change that to...

    addressString = "" + addressKey;

    Easier to read. Only issue is if it is not a number it gets written.


  • Registered Users Posts: 7,155 ✭✭✭witnessmenow


    not to late in the code scheme of things, too late in a deadline scheme of things!!

    reinforcement learning project (+ report) due by friday as you can see i'm a bit away yet!! I'm sure i'll be back for more help by then!

    thanks again


  • Advertisement
Advertisement