Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Java File IO problems

Posted on 2010-01-02
5
Medium Priority
?
772 Views
Last Modified: 2013-12-22
I am attempting to create a Java Program is a secret phrase game.  It is supposed to pull the phrases from a .dat file and then let the user guess the letters one at a time until they guess the entire phrase.  I was able to get it mostly working without using the Java IO methods (standard String vars, etc) but now that I have added the IO portion I get constant crashes and it's to the point where I can't even debug.  The first time I am able to debug partially but after each time I attempt to debug it gets slower and slower and then eventually locks up.  I'm guessing that maybe I need to close the connection to the file somehow which is why it gets slow and then crashes.  I guess my question is 2 fold.  Is there anything glaringly wrong with my code and/or how should I be trash collecting once I have opened the file?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

	
public class SecretPhraseUsingFile extends JApplet implements ActionListener
{
	public final int NUM_OF_LETTERS = 26;
	public final String[] letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
												 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
	public String secretPhrase;
	public StringBuffer maskedSecretPhrase = new StringBuffer("");
	public boolean isLetterInString = false;
	
	//create container, labels and buttons
	Container con = getContentPane();
	Font headlineFont = new Font("Helvetica", Font.BOLD, 36);
	Font titleFont = new Font("Helvetica", Font.BOLD, 14);
   JLabel header = new JLabel("Secret Phrase game");
	JLabel instructions = new JLabel("Play our game - guess the phrase  Enter one letter");
	JLabel maskedLabel = new JLabel();
   JLabel command = new JLabel();
	JLabel status = new JLabel();
	JButton[] alphabet = new JButton[NUM_OF_LETTERS];
	DataInputStream istream;
	
	public SecretPhraseUsingFile()
	{
		try
		{
			istream = new DataInputStream(new FileInputStream("SecretPhrases.dat"));
			secretPhrase = istream.readUTF();
		}
		catch(EOFException e2)
		{
			closeFile();
		}
		catch(IOException e3)
		{
			System.err.println("Error reading file");
			System.exit(1);
		}
		
		BuildPhraseMask();
		maskedLabel.setText(maskedSecretPhrase.toString());
	}
   
	private void checkString(String ltr)
	{
		int x = 0;
		char c = ltr.charAt(0);
		char y;
		int position;
		
		while(x < secretPhrase.length())
		{
			//Replace * with letter in masked secret phrase if user guesses a letter correctly
			y = secretPhrase.charAt(x);
			if(y == c)
			{
				maskedSecretPhrase.setCharAt(x, c);
				status.setText("Correct");
				maskedLabel.setText(maskedSecretPhrase.toString());
				isLetterInString = true;
			}
			
			x++;
		}
	}
		
   public void init()
   {
   	//fill container with labels and a buttons
		header.setFont(headlineFont);
		instructions.setFont(titleFont);
		status.setFont(titleFont);
		maskedLabel.setFont(titleFont);
		
		con.setLayout(new FlowLayout());
      con.add(header);
      con.add(instructions);
		con.add(maskedLabel);
		con.add(status);
		
		//add all 26 letters of alphabet to buttons
		for(int i = 0; i < NUM_OF_LETTERS; i++)
		{
			con.add(alphabet[i] = new JButton());
			alphabet[i].setText(letters[i]);
			alphabet[i].addActionListener(this);
		}
   }
   
   public void actionPerformed(ActionEvent e)
   {
	/*
		try
		{
			istream = new DataInputStream(new FileInputStream("SecretPhrases.dat"));
			secretPhrase = istream.readUTF();
		}
		catch(EOFException e2)
		{
			closeFile();
		}
		catch(IOException e3)
		{
			System.err.println("Error reading file");
			System.exit(1);
		}
		
		BuildPhraseMask();
		maskedLabel.setText(maskedSecretPhrase.toString());
		*/
		String s;
		Object source = e.getSource();
		JButton button = (JButton)source;
		button.setEnabled(false);
		s = button.getText();
		//checkString(s);
	}
	
	public void closeFile()
	{
		try
		{
			istream.close();
			System.exit(0);
		}
		catch(IOException e4)
		{
			System.err.println("Error closing file");
			System.exit(1);
		}
	}
	
	public void BuildPhraseMask()
	{
		int x = 0;
		char y;
		int position;
		
		while(x < secretPhrase.length())
		{
			y = secretPhrase.charAt(x);
			
			if(Character.isLetter(y))
				maskedSecretPhrase.append("*");
			else if(Character.isSpace(y))
				maskedSecretPhrase.append(" ");
		}
			
		x++;
	}
}

Open in new window

0
Comment
Question by:rufustmac
  • 2
  • 2
5 Comments
 
LVL 11

Expert Comment

by:nordtorp
ID: 26162947
If I understand correctly, you read a word from a file and then keeps it in memory, correct?

What if you store it in a string and then close the file, would that help?
0
 

Author Comment

by:rufustmac
ID: 26162984
Correct.  I have a separate application that allows a user to store the secret phraseand then this application opens that .dat file to read the secret phrase.  In the constructor I open the file and store it to a variable.  I just tried closing the file right after I was done saving it and it's still crashing so it may be something else.  Do you see anything incorrect in my code that might be causing it to crash?
0
 
LVL 11

Expert Comment

by:nordtorp
ID: 26163011
Do you know if it crash on the same place every time, or is it always different places?
Do you have any line number were it stops?
Have you tried to set breakpoints and then run through one and one until it crash?
Does it crash after you have made a guess and returned it to the program to verify the input?
Does it crash because you enter 'a' instead of 'A'?

0
 
LVL 10

Accepted Solution

by:
Pramod Kumar earned 2000 total points
ID: 26168777
There were few bugs in your code which i have fixed and attached here....


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.io.*;

	
public class SecretPhraseUsingFile extends JApplet implements ActionListener
{
	public final int NUM_OF_LETTERS = 26;
	public final String[] letters = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", 
												 "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
	public String secretPhrase;
	public StringBuffer maskedSecretPhrase = new StringBuffer("");
	public boolean isLetterInString = false;
	
	//create container, labels and buttons
	Container con = getContentPane();
	Font headlineFont = new Font("Helvetica", Font.BOLD, 36);
	Font titleFont = new Font("Helvetica", Font.BOLD, 14);
   JLabel header = new JLabel("Secret Phrase game");
	JLabel instructions = new JLabel("Play our game - guess the phrase  Enter one letter");
	JLabel maskedLabel = new JLabel();
   JLabel command = new JLabel();
	JLabel status = new JLabel();
	JButton[] alphabet = new JButton[NUM_OF_LETTERS];
    FileInputStream istream;
	public SecretPhraseUsingFile()
	{
		try
		{
            istream = new FileInputStream("c:\\SecretPhrases.dat");
            byte b[] = new byte[istream.available()];
            istream.read(b);
            secretPhrase = new String(b);
		}
		catch(EOFException e2)
		{
			closeFile();
		}
		catch(IOException e3)
		{
			System.err.println("Error reading file");
			System.exit(1);
		}
		
		BuildPhraseMask();
		maskedLabel.setText(maskedSecretPhrase.toString());
	}
   
	private void checkString(String ltr)
	{
		int x = 0;
		char c = ltr.charAt(0);
		char y;
		int position;
		
		while(x < secretPhrase.length())
		{
			//Replace * with letter in masked secret phrase if user guesses a letter correctly
			y = secretPhrase.charAt(x);
			if(y == c)
			{
				maskedSecretPhrase.setCharAt(x, c);
				status.setText("Correct");
				maskedLabel.setText(maskedSecretPhrase.toString());
				isLetterInString = true;
			}
			
			x++;
		}
	}
		
   public void init()
   {
   	//fill container with labels and a buttons
		header.setFont(headlineFont);
		instructions.setFont(titleFont);
		status.setFont(titleFont);
		maskedLabel.setFont(titleFont);
		
		con.setLayout(new FlowLayout());
      con.add(header);
      con.add(instructions);
		con.add(maskedLabel);
		con.add(status);
		
		//add all 26 letters of alphabet to buttons
		for(int i = 0; i < NUM_OF_LETTERS; i++)
		{
			con.add(alphabet[i] = new JButton());
			alphabet[i].setText(letters[i]);
			alphabet[i].addActionListener(this);
		}
   }
   
   public void actionPerformed(ActionEvent e)
   {
	/*
		try
		{
			istream = new DataInputStream(new FileInputStream("SecretPhrases.dat"));
			secretPhrase = istream.readUTF();
		}
		catch(EOFException e2)
		{
			closeFile();
		}
		catch(IOException e3)
		{
			System.err.println("Error reading file");
			System.exit(1);
		}
		
		BuildPhraseMask();
		maskedLabel.setText(maskedSecretPhrase.toString());
		*/
		String s;
		Object source = e.getSource();
		JButton button = (JButton)source;
		button.setEnabled(false);
		s = button.getText();
		//checkString(s);
	}
	
	public void closeFile()
	{
		try
		{
			istream.close();
			System.exit(0);
		}
		catch(IOException e4)
		{
			System.err.println("Error closing file");
			System.exit(1);
		}
	}
	
	public void BuildPhraseMask()
	{
		int x = 0;
		char y;
		int position;
		
		while(x < secretPhrase.length())
		{
			y = secretPhrase.charAt(x);
			
			if(Character.isLetter(y))
				maskedSecretPhrase.append("*");
			else if(Character.isSpace(y))
				maskedSecretPhrase.append(" ");

            x++;
		}
			

	}
}

Open in new window

0
 

Author Closing Comment

by:rufustmac
ID: 31674914
Can you tell me what I had wrong?  I had to change from using an applet but all the other code you supplied works fine.  Thanks.
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month10 days, 10 hours left to enroll

572 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question