Here's a program that will accept a text file (.txt, not Microsoft word or pdf stuff, just a basic text file) as a COMMAND LINE ARGUMENT and store each word (accepting ALL punctuation as if it were a space character, including apostrophe's) in a binary tree. Each node in the tree stores an ArrayList which holds the number of times that word occurs(first element) and each position in the text file that it occurs (all following elements). The user is shown the total number of words, and you can search for a word to see how many times and where in the file it is stored.
The code is not mine the autor is MasudKhan, i'm learning with it how to do my own code for a similar program.
I have been having some trouble finding the error with this code and why it's not working, the error message is:
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at A3Driver.main(A3Driver.java:10)"
A3Driver.java
/**
Assignment3
This class is a driver for a program which reads in a file,
whose name is given as a command line argument, and stores each
word as well as how many occurences of that word and the positions of
each occurence in the text file. The program then offers to allow
the user to search for any input word and produce the info for it,
if any.
*/
import java.io.*;
import java.util.*;
public class A3Driver
{
/**
main method for Binary word search program.
*/
public static void main(String[] args)
{
WordBST newTestWordBST = new WordBST(new File(args[0]));
System.out.println("Total number of words in file: " +
WordBST.wordPosition);
System.out.println("Number of unique words in file: " +
WordBST.uniqueWordCount);
System.out.print("Most used word: " + WordBST.mostUsedWord);
System.out.println(", times used: " + WordBST.highestCount);
System.out.println("\n\n");
Scanner keyboard = new Scanner(System.in);
String input = "";
while(!input.equals("n"))
{
System.out.print("Search for word (y/n)? ");
input = keyboard.nextLine();
if(input.toLowerCase().equals("y"))
{
System.out.print("Enter word: ");
newTestWordBST.searchBinaryTree(keyboard.nextLine());
}
}
System.out.println("Thank you, goodbye.");
/**
To output all tree info, uncomment this section.
newTestWordBST.inOrderTraverse();
*/
}
}
WordBST.java
/**
Assignment3
This class holds a Binary search tree of WordBSTNodes.
*/
import java.io.*;
import java.util.*;
public class WordBST
{
WordBSTNode root;
static int wordPosition, uniqueWordCount = 0, highestCount;
static String mostUsedWord;
/**
Constructor: initializes the root to null.
*/
public WordBST()
{
root = null;
}
/**
Constructor: initializes root to parameter value.
#param theRoot the root of this WordBST object
*/
public WordBST(WordBSTNode theRoot)
{
root = theRoot;
}
/**
Constructor: initializes root to hold nodes containing the words and
data from the parameter file.
#param text the input file containing words
*/
public WordBST(File text)
{
try
{
BufferedReader bR = new BufferedReader(new FileReader(text));
root = readBinaryTree(bR);
}
catch(IOException e)
{
System.out.println("Error reading file. Exiting.");
System.exit(1);
}
}
/**
Wrapper method for the recursive add method.
#param item the item to add to the BST
*/
public void add(String item)
{
root = add(root, item);
}
/**
Postcondition: uses recursion to add item to the BST node in the
appropriate position, or add information to the matching node.
#param localRoot the local node being checked in the current call
#param item the item to add to the BST
*/
private WordBSTNode add(WordBSTNode localRoot, String item)
{
if(localRoot == null) // item not in tree - add it
{
uniqueWordCount++; // total distinct word count
ArrayList<Integer> temp = new ArrayList<Integer>();
temp.add(1);
temp.add(wordPosition);
return new WordBSTNode(item, temp);
}
else if(item.compareTo(localRoot.word) == 0) // item == localRootData
{
localRoot.countAndPos.set(0, localRoot.countAndPos.get(0) + 1);
localRoot.countAndPos.add(wordPosition);
if(localRoot.countAndPos.get(0) > highestCount)
{
highestCount = localRoot.countAndPos.get(0);
mostUsedWord = localRoot.word;
}
return localRoot;
}
else if(item.compareTo(localRoot.word) < 0) //item < localRootData
{
localRoot.leftTree = add(localRoot.leftTree, item);
return localRoot;
}
else // item > localRootData
{
localRoot.rightTree = add(localRoot.rightTree, item);
return localRoot;
}
}
/**
Postcondition: performs an inorder traversal.
*/
public void inOrderTraverse()
{
inOrderTraverse(root);
}
/**
Perform an inorder traversal.
#param localRoot the current node being traversed
*/
private void inOrderTraverse(WordBSTNode localRoot)
{
if(localRoot.leftTree != null) // left
{
inOrderTraverse(localRoot.leftTree);
}
// middle
//output current root
System.out.print(localRoot.word);
for(int i = 0; i < localRoot.countAndPos.size(); i++)
{
System.out.print(", " + localRoot.countAndPos.get(i));
}
System.out.println();
if(localRoot.rightTree != null) // right
{
inOrderTraverse(localRoot.rightTree);
}
}
/**
Wrapper method for searchBinaryTree recursive method.
#param searchWord the String word to search for
*/
public void searchBinaryTree(String searchWord)
{
searchBinaryTree(searchWord, root);
}
/**
Postcondition: if word is found in the search, it is output along with
occurrence information, and if it is not found, not-found info is output.
#param searchWord the word to search for
#param localRoot the localRoot being checked in the current call
*/
public void searchBinaryTree(String searchWord, WordBSTNode localRoot)
{
if( (searchWord.compareTo(localRoot.word) < 0) &&
(localRoot.leftTree != null) )
{
searchBinaryTree(searchWord, localRoot.leftTree);
}
else if( (searchWord.compareTo(localRoot.word) > 0) &&
(localRoot.rightTree != null) )
{
searchBinaryTree(searchWord, localRoot.rightTree);
}
else if(searchWord.compareTo(localRoot.word) == 0)
{
System.out.println("Position number(s) of occurence(s):");
for(int i = 1; i < localRoot.countAndPos.size(); i++)
{
System.out.println("word #" + localRoot.countAndPos.get(i));
}
System.out.println("Word found.");
System.out.println("Occurences: " +
localRoot.countAndPos.get(0));
}
else
{
System.out.println("Word does not exist.");
}
}
/**
#param bR the bufferedReader to read from
#return returns a node containing the info from the file which the input
BufferedReader is reading from
*/
public WordBSTNode readBinaryTree(BufferedReader bR)
{
String data = "";
String temp;
try
{
while(bR.ready())
{
data = data.concat(bR.readLine().toLowerCase() + "\n");
}
if(data == "")
{
return null;
}
}
catch(IOException e)
{
System.out.println("Error reading file. Exiting.");
System.exit(1);
}
return readBinaryTree(
new StringTokenizer(data,
" \t\n\r\f.,!`'-\"\\:()[]{}=+_*&^%$##?<>;|/~"));
}
/**
#param inputST the StringTokenizer to repeatedly add words from
#return returns a node containing the info from the file which the input
BufferedReader is reading from
*/
public WordBSTNode readBinaryTree(StringTokenizer inputST)
{
wordPosition = 1;
ArrayList<Integer> tempArrayList =
new ArrayList<Integer>(wordPosition++);
tempArrayList.add(1);
WordBST tempBST = new WordBST(
new WordBSTNode(inputST.nextToken(), tempArrayList));
highestCount = 1;
mostUsedWord = tempBST.root.word;
while(inputST.hasMoreTokens())
{
tempBST.add(inputST.nextToken());
wordPosition++; // current position, and total words in file
}
return tempBST.root;
}
}
WordBSTNode.java
/**
Assignment3
This class holds a node for a binary search tree. The node includes
a pointer to it's left subtree and it's right subtree, as well as String
data, and an ArrayList containing the number of occurences of the
data in the user's input file in the first position, followed by the
word number in each following position.
*/
import java.util.*;
public class WordBSTNode
{
WordBSTNode leftTree;
WordBSTNode rightTree;
String word;
ArrayList<Integer> countAndPos;
/**
Constructor: no arg constructor must never be used to avoid
confusion between a null node element and a null element content.
*/
public WordBSTNode()
{
System.out.println("Cannot creat empty node, sorry.");
}
/**
Constructor: initializes parent, word, and countAndPos instance
variables.
#param theWord the word to be stored in this node
#param theCountAndPos an ArrayList containing this node's word's
count and position's
*/
public WordBSTNode(String theWord, ArrayList<Integer> theCountAndPos)
{
leftTree = null;
rightTree = null;
word = theWord;
countAndPos = theCountAndPos;
}
}
Any help is really apreciated.
Related
So basically, the idea is as follows:
The program must extend JTextPane
The program must detect when user typed an abbreviation in the extended JTextPane.
If the user keeps his caret at the last position of the abbreviation, and presses CTRL + ENTER, the program must replace that abbreviation with a definition.
My question is, how would that be done, would somebody be able to make a demo to demonstrate that?
I am aware that keyListener is not the best approach here.
Update A few hours later:
I managed to get it working finally.
I will write down my working demo down below, I hope it will save you the headache that I had to go through while working on it.
GIF Demonstration:
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.WindowConstants;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
/**
* JTextPane with capability to:
* -To keep the correct amount of tabs on new line when user types Enter
* -Dynamically add abbreviations
* -To replace abbreviation with its definition when user keeps caret at last letter of the abbreviation and taps CTRL + ENTER
* -To set position of the caret for each abbreviation after it is replaced by its definition
*/
public class AbbreviationJTextPane extends JTextPane {
public static void main(String[] args) {
JFrame frame = new JFrame();
// Create abbreviation JTextPane
AbbreviationJTextPane abbreviationPane = new AbbreviationJTextPane();
// Add abbreviations
abbreviationPane.addAbbreviation("sysout", "System.out.println();", 19); // 19 sets caret between parenthesis ( )
abbreviationPane.addAbbreviation("/**", "/*\n * \n * \n * /", 6); // 6 sets caret on second line after *
abbreviationPane.addAbbreviation("sob", "short of breath", 15);
// Add abbreviation JTextPane to JFrame
frame.add(abbreviationPane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setTitle("Demo on abbreviation with CTRL + ENTER capability for JTextPane");
frame.setSize(720, 250);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private AbbreviationList abbreviations = new AbbreviationList();
public void addAbbreviation(String abbreviation, String definition, int setCaretPositionBack) {
abbreviations.add(new AbbreviationParameter(setCaretPositionBack, abbreviation, definition));
}
public AbbreviationJTextPane() {
// Add key detection functional
InputMap im = getInputMap();
ActionMap am = getActionMap();
// Add ENTER Listener - Replaces the way ENTER key works - new line will keep the same amount of tabs as on previous line
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");
am.put("onEnter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
onEnter();
}
});
// Add CTRL + ENTER Listener
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK), "onCTRL_ENTER");
am.put("onCTRL_ENTER", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
onCtrlEnter();
}
});
}
// ====================== LISTENERS
/**
* Overrides the way tapping Enter key functions.
* New line "\n" will keep the same amount of tabs "\t" as on previous line
*/
private void onEnter() {
newLineWithTabs();
}
/**
* Overrides the way tapping CTRL + ENTER functions
*/
private void onCtrlEnter() {
// The method below must be called like this to avoid bugs where expanding does
// not work on new line
expandAbbreviation(" ");
expandAbbreviation("\n");
expandAbbreviation("\t");
}
// ====================== FUNCTIONAL
/**
* Inserts a new line.
* New line "\n" will keep the same amount of tabs "\t" as on previous line
*/
private void newLineWithTabs() {
try {
// Get the entire text in the document
String text = getDocument().getText(0, getCaretPosition());
// Get the end index of the text
int end = text.length();
// Insert relevant amount of tabs on each new line:
String tabs = getTabsFromLine(text, end);
// Replace all new lines in definition with relevant amount of tabs
String definition = "\n".replace("\n", "\n"+tabs);
// Insert the definition into the document at the start index
getDocument().insertString(end, definition, null);
} catch (BadLocationException e) {
e.printStackTrace();
}
}
/**
* This method is used to expand an abbreviation in the document based on the
* given word.
*
* #param lastIndexOf - a String representing the word that the abbreviation is
* being searched from
*/
private void expandAbbreviation(String lastIndexOf) {
try {
// Get the caret position in the document
int caretPosition = getCaretPosition();
Document doc = getDocument();
// Get the entire text in the document
String text = doc.getText(0, caretPosition);
// Get the start index of the word that is being searched
int start = text.lastIndexOf(lastIndexOf) + 1;
// Get the end index of the text
int end = text.length();
// Get the word that is being searched
String word = text.substring(start, end);
// Check if the abbreviations list contains the word and the caret position is
// at the end of the document
if (abbreviations.containsAbbreviation(word) && caretPosition == end) {
// Get the definition of the word from the abbreviations list
AbbreviationParameter inputParameter = abbreviations.getObjectForAbbreviation(word);
// If input parameter is null, this means that no such abbreviation exists in
// the list
if (inputParameter == null) {
return;
}
// Get definition from inputParameter
String definition = inputParameter.definition;
// Insert relevant amount of tabs on each new line:
String tabs = getTabsFromLine(text, end);
// Replace all new lines in definition with relevant amount of tabs
definition = definition.replace("\n", "\n"+tabs);
// Remove the word from the document
doc.remove(start, end - start);
// Insert the definition into the document at the start index
doc.insertString(start, definition, null);
// Set caret onto the appropriate index
setCaretPosition(start + inputParameter.caretPosition);
}
} catch (BadLocationException e) {
// No need to print anything as BadLocationException error will keep happening
// e.printStackTrace();
}
}
// ====================== UTILITY METHODS
/**
* Gets the tabs from line.
*
* #param text - the entire text in the document
* #param end - the end index of the text
* #return the tabs from line, string will be "" if there are no tabs at all
*/
private String getTabsFromLine(String text, int end) {
// Count all tabs in the line where caret is at present
int tabsCount = countCharacter(getLineAtIndex(text, end), '\t');
// Create String containing the amount of tabs necessary
StringBuilder tabs = new StringBuilder();
for(int iTab = 0; iTab < tabsCount; iTab++) {
tabs.append("\t");
}
return tabs.toString();
}
/**
* Returns the full line of a given index in a string.
*
* #param input the input string
* #param index the index in the input string
* #return the full line of the given index
*/
public static String getLineAtIndex(String input, int index) {
// Find the start index of the line
int start = input.lastIndexOf("\n", index) + 1;
// Find the end index of the line
int end = input.indexOf("\n", index);
if (end == -1) {
end = input.length();
}
// Return the substring from the start to the end of the line
return input.substring(start, end);
}
/**
* Count the number of a specified character in a string.
*
* #param s the input string
* #param c the character to count
* #return the number of occurrences of the character in the string
*/
public static int countCharacter(String s, char c) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == c) {
count++;
}
}
return count;
}
/**
* Count the number of occurrences of a specified string in another string.
*
* #param input the input string
* #param target the string to count
* #return the number of occurrences of the target string in the input string
*/
public static int countString(String input, String target) {
int count = 0;
int index = 0;
while ((index = input.indexOf(target, index)) != -1) {
count++;
index += target.length();
}
return count;
}
}
/**
* Constructor class for abbreviations, their definition, and expected caret
* location after use
*
*/
class AbbreviationParameter {
/**
* This value is meant to indicate how many chars forward the caret should be
* placed onto after definition is placed.
*/
final int caretPosition;
final String abbreviation;
final String definition;
public AbbreviationParameter(int caretPosition, String abbreviation, String definition) {
this.caretPosition = caretPosition;
this.abbreviation = abbreviation;
this.definition = definition;
}
/**
* Gets the definition.
*
* #return the definition
*/
public String getDefinition() {
return definition;
}
}
/**
* List with all abbreviations and their values
*/
class AbbreviationList extends ArrayList<AbbreviationParameter> {
private static final long serialVersionUID = -7332763119043404932L;
/**
* Checks if list contains given abbreviation.
*
* #param abbreviation - the abbreviation
* #return true, if successful
*/
public boolean containsAbbreviation(String abbreviation) {
ArrayList<AbbreviationParameter> list = this;
for (AbbreviationParameter stringInputParameter : list) {
if (stringInputParameter.abbreviation.equals(abbreviation)) {
return true;
}
}
return false;
}
/**
* Gets the object for abbreviation.
*
* #param abbreviation - the abbreviation
* #return the {#link #AbbreviationList} object for abbreviation given if match is found, will return null if no such abbreviation is found
*/
public AbbreviationParameter getObjectForAbbreviation(String abbreviation) {
ArrayList<AbbreviationParameter> list = this;
for (AbbreviationParameter stringInputParameter : list) {
if (stringInputParameter.abbreviation.equals(abbreviation)) {
return stringInputParameter;
}
}
return null;
}
}
I am working on some homework and have encountered a problem. The program creates a Tree, outputs pre/in/postorder traversals, then saves them to multiple files. The problem I'm having is getting the input. When you type in the input, after you're done typing in what should be the values of different Nodes, you may either type "done" or "exit". "Done" continues the program with the given input, while "exit" just closes the program. The weird thing is, you don't need to type the values of the Nodes twice to create those Nodes later on in the code, but you do have to type "done" or "exit" twice to get the program to listen to you. The code in question is here:
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(scanner.hasNext() && !response.equals("exit") && !response.equals("done")) {
fileWriter.write(response + " ");
response = scanner.next();
}
I have found that removing scanner.hasNext() gets it to function properly, but then it takes away sensing the EOF which is necessary for this assignment.
Here are the full three classes used in the program:
P0:
/**
* Sources for this class:
* https://www.w3schools.com/java/java_regex.asp
* https://stackoverflow.com/questions/14353947/how-to-represent-a-single-space-character-in-a-square-bracket-group
* https://upload.wikimedia.org/wikipedia/commons/1/1b/ASCII-Table-wide.svg
*
* Sources for shell script and makefile:
* https://www.cyberciti.biz/faq/run-execute-sh-shell-script/
* https://www.dummies.com/article/technology/computers/operating-systems/linux/linux-how-to-run-make-150284/
* https://www.cs.swarthmore.edu/~newhall/unixhelp/javamakefiles.html
*/
package mikefitzgibbon.p0;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class P0{
public static void main(String args[]) {
File file = new File("file");
String input = "";
//there can only be one or 0 arguments in the command line operation
if(args.length > 1) {
System.out.println("Please only enter the name of 1 file.");
System.exit(1);
}
//if a filename is specified, try getting the input from it
else if(args.length == 1){
file = new File(args[0]);
}
//else read from System.in
else {
Scanner scanner = new Scanner(System.in);
String response;
file = new File("input");
try (FileWriter fileWriter = new FileWriter(file)) {
System.out.println("Please enter strings to put into the tree.");
System.out.println("Type \"done\" to end taking in input, and type \"exit\" to prematurely quit.");
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(scanner.hasNext() && !response.equals("exit") && !response.equals("done")) {
fileWriter.write(response + " ");
response = scanner.next();
}
//exits the program with OK return value
if(response.equals("exit")) {
System.out.println("Prematurely ending program now.");
System.exit(0);
}
}
catch(IOException e){
System.out.println("Had trouble writing to file from System.in.");
}
}
//scans file for strings until there are no more data or eof is reached
try(Scanner scanner = new Scanner(file)){
while(scanner.hasNextLine()){
input += scanner.nextLine() + " ";
}
scanner.close();
}
//exit the program is file name is invalid
catch(FileNotFoundException e){
System.out.println("The file name you entered does not exist.");
System.exit(2);
}
//checks input for characters outside of the appropriate ASCII range
for(char c : input.toCharArray()){
if(!Character.isLetterOrDigit(c) &! Character.isWhitespace(c)) {
System.out.println("Your file or console input was not readable."
+ "\nPlease only use alhpanumeric characters.");
System.exit(3);
}
}
//this is only used as a reference for the filename
if(file.getName().equals("input"))
file = new File("output");
//creates the tree from the input and then converts it to the output
Tree tree = new Tree(input);
//displays the input
System.out.println("Here is your input for the program.");
System.out.println(input);
System.out.println();
//writes to the files
System.out.println("Outputting data to files " +
file.getName() + ".preorder, " +
file.getName() + ".inorder, and " +
file.getName() + ".postorder.");
System.out.println();
System.out.println("Output for " + file +".preorder: ");
tree.printPreorder(file.getName());
System.out.println();
System.out.println("Output for " + file +".inorder: ");
tree.printInorder(file.getName());
System.out.println();
System.out.println("Output for " + file +".postorder: ");
tree.printPostorder(file.getName());
System.out.println();
System.out.println("Ending program now.");
}
}
Tree:
/**
* Sources for this class:
* https://www.w3schools.com/java/java_files_create.asp
* https://www.softwaretestinghelp.com/binary-search-tree-in-java/
* https://www.youtube.com/watch?v=WLvU5EQVZqY&ab_channel=TECHDOSE
*/
package mikefitzgibbon.p0;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Tree {
//nodes that make up this part of the tree
Node root;
//constructor calls the buildTree() function
public Tree(String input){
buildTree(input);
}
//takes a list of strings and a root node and creates the tree structure recursively using the addNode helper function
private void buildTree(String input) {
Scanner scanner = new Scanner(input);
//recursively builds tree with each word
while(scanner.hasNext()){
root = addNode(root,scanner.next());
}
}
private Node addNode(Node root, String value){
//checks root for null and sets it if it is
if(root == null){
root = new Node(value);
return root;
}
//compares the first letter of the input to the root's value and recursively traverses tere
else if(root.getValue().charAt(0) > value.charAt(0))
root.setLeftNode(addNode(root.getLeftNode(),value));
else if(root.getValue().charAt(0) == value.charAt(0))
root.setMiddleNode(addNode(root.getMiddleNode(),value));
else if(root.getValue().charAt(0) < value.charAt(0))
root.setRightNode(addNode(root.getRightNode(),value));
//return root if all else fails
return root;
}
//prints the tree printPreorder recursively
public void printPreorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".preorder")) {
printPreorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the preorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the preorder file.");
}
}
//helper function for printPreorder()
private void printPreorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
try{
String indent = "";
for(int a = 0 ; a < depth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.println(indent + root.getValue().charAt(0) + ":" + root.getValue());
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .preorder file.");
System.exit(4);
}
depth++;
printPreorder(fileWriter, root.getLeftNode(), depth);
printPreorder(fileWriter, root.getMiddleNode(), depth);
printPreorder(fileWriter, root.getRightNode(), depth);
}
//prints the tree printInorder recursively
public void printInorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".inorder")) {
printInorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the inorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the inorder file.");
}
}
//helper function for printInorder()
private void printInorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
int previousDepth = depth;
depth++;
printInorder(fileWriter, root.getLeftNode(), depth);
try{
String indent = "";
for(int a = 0 ; a < previousDepth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.print(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .preorder file.");
System.exit(4);
}
printInorder(fileWriter, root.getMiddleNode(), depth);
printInorder(fileWriter, root.getRightNode(), depth);
depth++;
}
//prints the tree printPostorder recursively
public void printPostorder(String filename){
try(FileWriter myWriter = new FileWriter(filename + ".postorder")) {
printPostorder(myWriter, root, 0);
myWriter.close();
System.out.println();
System.out.println("Successfully wrote to the postorder file.");
}
catch (IOException e) {
System.out.println("An error occurred while writing to the postorder file.");
}
}
//helper function for printPostorder()
private void printPostorder(FileWriter fileWriter, Node root,int depth) {
//base case
if(root == null)
return;
//write to file and recursive cases
int previousDepth = depth;
depth++;
printPostorder(fileWriter, root.getLeftNode(), depth);
printPostorder(fileWriter, root.getMiddleNode(), depth);
printPostorder(fileWriter, root.getRightNode(), depth);
try{
String indent = "";
for(int a = 0 ; a < previousDepth ; a++){
indent += " ";
}
fileWriter.write(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
System.out.print(indent + root.getValue().charAt(0) + ":" + root.getValue() + "\n");
}
catch(IOException e){
System.out.println("Something went wrong while writing to the .postorder file.");
System.exit(4);
}
}
//getter and setter
public void setRoot(Node node) {
root = node;
}
public Node getRoot() {
return root;
}
}
Node:
/**
* Sources for this class:
* https://www.softwaretestinghelp.com/binary-search-tree-in-java/
*/
package mikefitzgibbon.p0;
public class Node {
//this is how the tree branches out, 3 children per node
Node left, middle, right;
String value = "";
public Node(String val) {
value=val;
}
//getters and setters
public void setRightNode(Node node) {
right=node;
}
public void setLeftNode(Node node) {
left=node;
}
public void setMiddleNode(Node node) {
middle=node;
}
public Node getRightNode() {
return right;
}
public Node getLeftNode() {
return left;
}
public Node getMiddleNode() {
return middle;
}
public String getValue() {
return value;
}
}
scanner.hasNext() will block (freeze the thread) until user input happens. You might think "No, it would return false, as currently there is no token available - there is no 'next'", but that's not how it works. There indeed may not currently be a next. But who knows what happens from here on out? Perhaps the user types CTRL+C, closing the pipe, thus, hasNext() will now return false, as there will never be a next token. Or, the user types something, and it will then return true, as now clearly there is a next token to be had. That's why it blocks: It cannot give a certain answer until you do something.
This may make no sense - keep in mind that 'standard input' is not the keyboard. It's... whatever stream is hooked up to standard input. By default that is a keyboard, but run your app with java -jar whatever.jar <somefile.txt and now it's that file. Which has a limited size. hasNext() would start returning false once you get to the 'end of the file'. You cannot normally ever get to the 'end of the keyboard', but the abstraction isn't designed solely for keyboards.
In other words, your code:
response = scanner.next();
while(scanner.hasNext() && ....
Will:
Read a token from standard input.
Will... read a token from standard input AGAIN (because hasNext() does that. If it works out, it returns true. If it turns out there is no token now nor will there ever be, it returns false).
This explain why you have to enter input twice. The solution is to remove the hasNext call there. Move it INTO the while loop. Instead of response = scanner.next() inside the loop, do something like:
if (!scanner.hasNext()) return; // or break, or System.exit(0), or whatever you want.
response = scanner.next();
}
I found that putting the scanner.hasNext() at the end of the expression fixed the problem, but I'm not entirely sure how. Here is the updated code:
//gets input from console until "exit" or "done" is typed
response = scanner.next();
while(!response.equals("exit") && !response.equals("done") && scanner.hasNext()) {
fileWriter.write(response + " ");
response = scanner.next();
}
Hi I am having issues printing and/or adding entries to my hash table I am looking to handle collisions with linear probing. Could someone help me? This is NOT a school project or assignment, just for fun.
I am new to the Java programming language.
I cannot get all of the entries to output to the console and I am wondering where I am going wrong.
/**
* File : ContactTable.java
* Project : None
* Programmer : Braiden Gole
* First version : 2020-05-20
* Description : This is the implementation of a hash table algorithm. We will be
* storing a record with three pieces of information for contacting
* a customer that is: First name, last name, email.
*/
import java.util.ArrayList;
import java.util.Scanner;
import java.util.InputMismatchException;
class ContactTable {
/** -- Class header comment
* Name : HashNode
* Purpose : This represents an entry in our hash table.
*/
static class HashNode {
String firstName;
String lastName;
String emailAddress;
int position;
HashNode next;
}
/** -- Class header comment
* Name : TableMapper
* Purpose : This class represents the operations that our hash table will be
* able to carry out.
*/
static class TableMapper {
private ArrayList<HashNode> hashTable = new ArrayList<>();
private final int KTABLELIMIT = 5;
/** -- Method header comment
* Method : initializeContactTable
* Description : This will add (null) markers so we can detect when a position
* has been filled with an entry or not.
* Parameters : None
* Returns : None
*/
private void initializeContactTable() {
for (int positions = 0; positions < KTABLELIMIT; positions++) {
hashTable.add(null);
}
}
/** -- Method header comment
* Method : hashMethod
* Description : This is the hash method to calculate the position at which the
* record of contact will sit in the contact table. We will be
* using the name field to store the record.
* Parameters : key
* Returns : hashValue % KTABLELIMIT
*/
private int hashMethod(String key) {
int hashValue = 0;
for (int letters = 0; letters < key.length(); letters++) {
hashValue += key.charAt(letters);
}
return hashValue % KTABLELIMIT;
}
/** -- Method header commment
* Method : insertRecord
* Description : This method will insert the entire object record into the
* has table. We will handle collisions with linear probing and
* make use of the "wrap around method."
* Parameters : key, position lastName, email
* Returns : currentSize
*/
private int insertRecord(String key, int position, String lastName, String email) {
HashNode checkPosition = hashTable.get(position);
HashNode newRecord = new HashNode();
// Check to make sure that the name does not already exist.
while (checkPosition != null) {
if ((checkPosition.firstName.equals(key)) == true) { return 1; }
checkPosition = checkPosition.next;
}
// The calculated position has been moved, recalculate.
checkPosition = hashTable.get(position);
if (checkPosition == null) {
newRecord.firstName = key;
newRecord.position = position;
newRecord.lastName = lastName;
newRecord.emailAddress = email;
newRecord.next = checkPosition;
hashTable.add(position, newRecord);
return 0;
} else {
while ((hashTable.get(position)) != null) {
++position;
position %= KTABLELIMIT;
}
newRecord.firstName = key;
newRecord.position = position;
newRecord.lastName = lastName;
newRecord.emailAddress = email;
newRecord.next = hashTable.get(position);
hashTable.add(position, newRecord);
return 0;
}
}
/** -- Method header comment
* Method : showContacts
* Description : This will display all contact records to the console.
* Parameters : None
* Returns : None
*/
private void showContacts() {
for (int entries = 0; entries < KTABLELIMIT; entries++) {
if ((hashTable.get(entries)) != null) {
System.out.println();
System.out.println(hashTable.get(entries).firstName);
System.out.println(hashTable.get(entries).lastName);
System.out.println(hashTable.get(entries).emailAddress);
}
}
}
}
public static void main(String[] args) {
TableMapper mapper = new TableMapper();
Scanner reader = new Scanner(System.in);
// The primaryKey is the users first name.
String primaryKey = "";
String lastName = "";
String email = "";
int index = 0;
int currentSize = 0;
int returnInsertVal = 0;
// Initialize the contact table with (null) markers.
mapper.initializeContactTable();
boolean contactEntryCondition = true;
while (contactEntryCondition) {
System.out.println();
System.out.print("Enter in your first name: ");
primaryKey = reader.next();
System.out.print("Enter in your last name: ");
lastName = reader.next();
System.out.print("Enter in your email address: ");
email = reader.next();
// Calculate the index at which the record will sit.
index = mapper.hashMethod(primaryKey);
// Use the calculated index to insert the record at the proper position.
returnInsertVal = mapper.insertRecord(primaryKey, index, lastName, email);
// When the table is full exit the loop and print the table.
if (currentSize == mapper.KTABLELIMIT) { contactEntryCondition = false; }
if (returnInsertVal == 0) { ++currentSize; }
else { primaryKey = ""; }
System.out.println(currentSize);
}
reader.close();
// Output the contact records.
mapper.showContacts();
}
}
after each hashTable.add(position, newRecord) your underlying list (hashTable) grows in size by one
void add(int index, E element)
Inserts the specified element at the specified position in this list (optional > operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
this messes up the "bookkeeping" that you do on the table.
in showContacts(), change the for line as follows:
for (int entries = 0; entries < hashTable.size(); entries++) {
and it will print all the elements inside the table.
you should rethink your implementation and use a "fixed size underlying list" (possibly an array) enlarging it only when it's necessary and rehashing when you do so.
when creating the list manually by keyboard I have the following drawback, the variable nodo only stores the current value. ListaEnlazada1 nodo = new ListaEnlazada1();
package lista.enlazada1;
import java.util.Scanner;
public class ListaEnlazada1 {
public String marca;
public String modelo;
public int kilometraje;
public ListaEnlazada1 nodosiguiente;
public static void main(String[] args) {
/* enter the number of nodes to be created */
Scanner leer= new Scanner(System.in);
System.out.println("Digite la cantidad de nodos a ingresar)");
int n,contador=0;
n=leer.nextInt();
/* the three data of the node is entered */
for (int i =1; i <= n; i++){
ListaEnlazada1 nodo = new ListaEnlazada1();
System.out.print("ingrese la marca ");
nodo.marca=leer.next();
System.out.print("ingrese el modelo ");
nodo.modelo=leer.next();
System.out.print("ingrese el kilometraje ");
nodo.kilometraje=leer.nextInt();
/* the node is created */
if(contador==0){
nodo.nodosiguiente = null;
contador ++;
} else {
nodo.nodosiguiente = nodo;
contador ++;
}
/* nodes are printed */
for ( i =1; i <= n; i++){
System.out.println("marca " +nodo.marca+ "\n");
System.out.println("modelo " +nodo.modelo+ "\n");
System.out.println("kilometraje " +nodo.kilometraje+ "\n");
System.out.println("apuntador " +nodo.nodosiguiente + "\n");
}
}
}
}
I need to change the code so that the variable changes the name every time I enter the for, for example the first iteration node1, the second iteration node2, etc. what I have tried nothing has worked. the exercise must be done without the linked list library
To display the current node's position in the series, consider the following:
for(int i = 1; i <= n; i++) {
System.out.println("----------");
System.out.println("Ingrese los datos del nodo " + i);
/* user input */
}
You might as well consider displaying information about each node after all nodes have been entered so that the program's output is more readable. Since you store each node in the node before it, you could try this to cycle through them:
ListaEnlazada actual = primerNodo; // save the first node somewhere before user input
imprimirNodo(actual);
while((actual = actual.nodosiguiente) != null) {
imprimirNodo(actual);
}
where the imprimirNodo(nodo) method is the following:
static void imprimirNodo(ListaEnlazada1 nodo) {
System.out.println("----------");
System.out.println("Marca: " + nodo.marca); // No need to break the line manually.
System.out.println("Kilometraje: " + nodo.kilometraje);
/* Note that printing nodo.nodosiguiente may lead to
* unreadable output unless you override toString() */
System.out.println("Apuntador: " + nodo.nodosiguiente);
}
I am creating the Sudoku game and I am trying to provide options to save, save as, and open games. I am using JFileChooser to do this. I am able to save (or "save as") but when I try to open a saved file, I get an error. I am new to programming and I'm hoping someone could spot the issue and educate me on how to read in the contents of the Sudoku board when I am saving (as well as how to deal with re-creating the Sudoku board when I open the file). I hear there is an easier way to deal with this using InputStream/OutputStream instead of Reader/Writer...
Here is my code for the inner class that implements this (I don't know if there's a way to post my entire class without exceeding the character limit for this text box.):
EDIT:
// this inner class provides a JMenuBar object at the top of
// the board
class MenuAtTop extends JMenuBar implements ActionListener{
// SudokuMain object we are dealing with
private SudokuMain main;
// the "File" menu
private JMenu fileMenu;
// the "New Game" option
private JMenuItem newGame;
// the "Open" option
private JMenuItem open;
// the "Save" option
private JMenuItem save;
// the "Save As" option
private JMenuItem saveAs;
// the "Reset" option
private JMenuItem reset;
// the "Quit" option
private JMenuItem quit;
// the ability to choose files
private JFileChooser choose;
// the saved file
// // compiler would not allow "static" keyword
private File fileSaved = null;
private Object opener;
// JDialog object to create a dialog box to prompt
// user for new game information
private JDialog createNewWin;
/**
* Constructs MenuAtTop object.
*
* #param m The SudokuMain object to be referred to.
*/
public MenuAtTop(final SudokuMain m) {
main = m;
opener = null;
choose = new JFileChooser();
// instantiate and bind to reference
fileMenu = new JMenu("File");
add(fileMenu);
// instantiate and bind to reference
newGame = new JMenuItem("New Game");
newGame.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
ActionEvent.CTRL_MASK));
fileMenu.add(newGame);
newGame.addActionListener(this);
open = new JMenuItem("Open");
open.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O,
ActionEvent.CTRL_MASK));
fileMenu.add(open);
// add action listener to "Open" option
open.addActionListener(this);
save = new JMenuItem("Save");
save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
ActionEvent.CTRL_MASK));
fileMenu.add(save);
// add action listener to "Save" option
save.addActionListener(this);
saveAs = new JMenuItem("Save As");
saveAs.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A,
ActionEvent.CTRL_MASK));
fileMenu.add(saveAs);
// add action listener to "Save As" option
saveAs.addActionListener(this);
reset = new JMenuItem("Reset");
reset.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
ActionEvent.CTRL_MASK));
fileMenu.add(reset);
// add action listener to "Reset" option
reset.addActionListener(this);
quit = new JMenuItem("Quit");
quit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q,
ActionEvent.CTRL_MASK));
fileMenu.add(quit);
// add action listener to "Quit" option
quit.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource().equals(newGame)) {
setEnabled(false);
// create dialog box prompting for the new board information
createNewWin = new Dialog1(main, "Create New Board", true);
// make it visible
createNewWin.setVisible(true);
fileSaved = null;
} else if(e.getSource().equals(open)) {
int returnVal = choose.showOpenDialog(main.win);
if(returnVal == JFileChooser.APPROVE_OPTION) {
boolean error = false;
File openFile = choose.getSelectedFile();
try {
FileInputStream fis = new FileInputStream(openFile);
ObjectInputStream ois = new ObjectInputStream(fis);
opener = ois.readObject();
SudokuBase sudoku = (SudokuBoard) opener;
ois.close();
} catch (Exception exc) {
exc.printStackTrace();
JOptionPane.showMessageDialog(main.win, "Error opening file.");
error = true;
}
// "opener" reads something and it is of type SudokuBase
if(opener != null && opener instanceof SudokuBase){
main.north.remove(main.rowColRegStates);
main.west.remove(main.symbols);
main.east.remove(main.view);
main.view = new SudokuView((SudokuBase) opener);
main.rowColRegStates = new ShowStates(main.view);
main.symbols = new SetSymbols(main.view);
main.north.add(main.rowColRegStates);
main.west.add(main.symbols);
main.east.add(main.view);
main.win.requestFocus();
fileSaved = openFile;
} else {
if(error) {
JOptionPane.showMessageDialog(main.win, "Incorrect file type.");
}
}
}
} else if(e.getSource().equals(save)) {
if(fileSaved == null) {
saveAsPrompt();
} else {
try {
FileOutputStream fos = new FileOutputStream(fileSaved);
ObjectOutputStream oos = new ObjectOutputStream(fos);
board.writeToStream(fos);
oos.writeObject(board);
oos.close();
} catch (Exception exc) {
JOptionPane.showMessageDialog(main.win, "Error saving file.");
}
}
} else if(e.getSource().equals(saveAs)) {
saveAsPrompt();
} else if(e.getSource().equals(reset)) {
int n = JOptionPane.showConfirmDialog(main.win,
"Any player values will" +
" be lost. Proceed?",
"Warning!", 2);
if(n == JOptionPane.OK_OPTION) {
main.board.reset();
main.view.repaint();
}
} else if(e.getSource().equals(quit)) {
closePrompt();
}
}
// This method prompts the user to choose a file to save to,
// and then saves the file.
private int saveAsPrompt() {
boolean saveError;
int rtn = choose.showSaveDialog(main.win);
if(rtn == JFileChooser.APPROVE_OPTION) {
saveError = false;
File fileSaveAs = choose.getSelectedFile();
try {
board.writeToStream(new FileOutputStream(fileSaveAs));
} catch (Exception e) {
JOptionPane.showMessageDialog(main.win, "Error saving file.");
saveError = true;
}
if(!saveError) {
fileSaved = fileSaveAs;
}
}
return rtn;
}
// This method prompts the user whether they want to save before
// closing, only if changes occurred.
private void closePrompt() {
if(true) {
int n = JOptionPane.showConfirmDialog(main.win, "Save game?");
if(n == JOptionPane.YES_OPTION) {
int saved = saveAsPrompt();
if(saved != JFileChooser.CANCEL_OPTION){
main.win.dispose();
}
} else if(n == JOptionPane.NO_OPTION) {
main.win.dispose();
}
}
else { // no changes were made
main.win.dispose();
}
}
}
Here's the class that holds the data (it is extended by SudokuBoard):
// Allow short name access to following classes
import java.util.Observable;
import java.io.InputStream;
import java.io.OutputStream;
public abstract class SudokuBase extends Observable {
// rows per region
private int rows;
// columns per region
private int columns;
// size of a region (rows * columns)
private int size;
// array of each element of entire sudoku board
private int[] grid;
// the masked 8-bit "given" value constant
private static final int GIVEN_MASK = 0x00000100;
// the bitwise complement of the masked "given" constant,
// which produces an unmasked constant
private static final int GIVEN_UNMASK = ~ GIVEN_MASK;
/**
* Enumerated type to store constants that indicate the "State" of
* a specified row, column, or region.
*/
public enum State {COMPLETE, INCOMPLETE, ERROR};
/**
* Constructs SudokuBase object.
*
* #param layoutRows The number of rows per region.
* #param layoutColumns The number of columns per region.
*/
public SudokuBase(int layoutRows, int layoutColumns) {
rows = layoutRows;
columns = layoutColumns;
size = columns * rows;
grid = new int[size*size];
}
/**
* Gets the number of rows per region.
*
* #return The rows per region.
*/
public int getRowsPerRegion() {
return rows;
}
/**
* Gets the number of columns per region.
*
* #return The columns per region.
*/
public int getColumnsPerRegion() {
return columns;
}
/**
* Gets the size of the region (rows * columns).
*
* #return The size of the region.
*/
public int getBoardSize() {
return size;
}
// gets the index of the specified row and column for the grid
private int getIndex(int row, int col) {
// handle invalid arguments
if(row < 0 || row >= size || col < 0 || col >= size) {
String msg = "Error in location";
throw new IllegalArgumentException(msg);
}
return row * size + col;
}
/**
* Gets the value of the element at the specified row
* and column on the grid.
*
* #param row The specified row.
* #param col The specified column.
* #return The value of the element at the specified row and column.
*/
public int getValue(int row, int col) {
return grid[getIndex(row, col)] & GIVEN_UNMASK;
}
/**
* Sets the desired value at the specified row and column.
*
* #param row The specified row.
* #param col The specified column.
* #param value The specified value to be set.
*/
public void setValue(int row, int col, int value) {
// handle invalid argument
if(value < 0 || value > size) {
String msg = "Value out of range: " + value;
throw new IllegalArgumentException(msg);
}
// handle attempt to set a value for a "given" location
if(isGiven(row, col)) {
String msg = "Cannot set given location: " + row + ", " + col;
throw new IllegalStateException(msg);
}
grid[getIndex(row, col)] = value;
setChanged();
notifyObservers();
}
/**
* This method checks the status of the "givens" bit.
*
* #param row The specified row.
* #param col The specified column.
* #return Whether or not the specified location is a "given" value.
*/
public boolean isGiven(int row, int col) {
return (grid[getIndex(row, col)] & GIVEN_MASK) == GIVEN_MASK;
}
/**
* This method sets non-zero values on the Sudoku board with the
* "givens" bit.
*/
public void fixGivens() {
for(int i = 0; i < grid.length; i++)
if(grid[i] != 0)
grid[i] |= GIVEN_MASK;
setChanged();
notifyObservers();
}
/**
* This abstract method gets the "State" (COMPLETE, INCOMPLETE,
* or ERROR) of the specified row.
*
* #param n The specified row.
* #return The "State" of the row.
*/
public abstract State getRowState(int n);
/**
* This abstract method gets the "State" (COMPLETE, INCOMPLETE,
* or ERROR) of the specified column.
*
* #param n The specified column.
* #return The "State" of the column.
*/
public abstract State getColumnState(int n);
/**
* This abstract method gets the "State" (COMPLETE, INCOMPLETE,
* or ERROR) of the specified region.
*
* #param n The specified region.
* #return The "State" of the region.
*/
public abstract State getRegionState(int n);
/**
* Represents the Sudoku board as a grid of appropriate characters.
*
* #return The string representation of the Sudoku board.
*/
public String toString() {
String board = "";
for(int i = 0; i < size; i ++) {
for(int j = 0; j < size; j ++)
board += charFor(i, j) + " ";
board += "\n";
}
return board;
}
// this method provides a character for all possible values encountered on the
// Sudoku board, to be utilized in "toString()"
private String charFor(int i, int j) {
int v = getValue(i, j);
// negative value (invalid)
if(v < 0) {
return "?";
} else if(v == 0) { // blank or zero value
return ".";
} else if(v < 36) { // value from 1 to (size * size)
return Character.toString(Character.forDigit(v, 36)).toUpperCase();
} else { // non-numeric input or v >= size * size (both invalid)
return "?";
}
}
/**
* This method reads from an input stream.
*
* #param is The input stream to read from.
*/
protected void readFromStream(InputStream is) {
}
/**
* This method writes to an output stream.
*
* #param os The output stream to write to.
*/
protected void writeToStream(OutputStream os) {
try {
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.close();
} catch(IOException e) {
}
}
/**
* Gets the "raw" value directly, not having checked whether there is an
* unfixed error message.
*
* #param row The row where the raw value is located.
* #param col The column where the raw value is located.
* #return The raw value.
*/
protected int getRawValue(int row, int col) {
return grid[getIndex(row, col)];
}
/**
* Sets the raw value directly, not having checked whether there is an
* unfixed error message.
*
* #param row The row where the raw value is to be located.
* #param col The column where the raw value is to be located.
*/
protected void setRawValue(int row, int col, int value) {
grid[getIndex(row, col)] = value;
}
protected void reset() {
for(int row = 0; row < rows; row++) {
for(int col = 0; col < columns; col++) {
if(!isGiven(row, col)) {
grid[getIndex(row, col)] = 0;
}
}
}
}
}
Well I cannot give a full answer and I do not want to browse the full source code. But a few pointers for you to find some solution:
Never catch Exceptions like that while developing an application:
} catch (Exception e) {
JOptionPane.showMessageDialog(main.win, "Error saving file.");
saveError = true;
}
With this, you completely loose the chance to detect errors. At least add the following line to your exception handling:
e.printStackTrace();
Normally you would log the exception and so on, but with that you see the source of your error at the console. Better than nothing.
To your more specific problem:
You seem to write an Object to a file holding all the configuration. In your read method something goes wrong. Probably you do not read the same object as you write or something like that. Hard to say without any code. Try to get the exception stack trace and figure out what the problem is. If you cannot figure it out, edit your question with more specific information and I will try to give better directions.
EDIT:
Here is a small example showing serialization of objects for a Sudoku like game:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class SerializationExample {
public static void main(String args[]) throws IOException, ClassNotFoundException {
final File target = new File(System.getProperty("java.io.tmp"), "mySerializedObject.txt");
Map<Integer, Integer> initialState = new HashMap<Integer, Integer>();
initialState.put(1, 1);
initialState.put(21, 3);
// ...
GameState state = new GameState(10, initialState);
state.setField(2, 2);
state.setField(3, 8);
System.out.println("Game state before writing to file: " + state);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(target));
out.writeObject(state);
out.close();
ObjectInputStream in = new ObjectInputStream(new FileInputStream(target));
Object gameStateReadFromFile = in.readObject();
GameState readGameState = (GameState)gameStateReadFromFile;
System.out.println("Read from file: " + readGameState);
}
private static class GameState implements Serializable {
private int[] fields;
private int boardSize;
private int[] fixedFields;
public GameState(int boardSize, Map<Integer, Integer> initialState) {
this.boardSize = boardSize;
this.fields = new int[boardSize * boardSize];
this.fixedFields = new int[this.fields.length];
for (Entry<Integer, Integer> entry : initialState.entrySet()) {
this.fixedFields[entry.getKey()] = entry.getValue();
}
}
public void setField(int index, int value) {
this.fields[index] = value;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("\nFixed fields: ");
appendArray(builder, this.fixedFields);
builder.append("\nSet fields: ");
appendArray(builder, this.fields);
return builder.toString();
}
private void appendArray(StringBuilder builder, int[] fieldArray) {
for (int i = 0; i < fieldArray.length; ++i) {
if (fieldArray[i] != 0) {
builder.append("row ").append(i / this.boardSize).append(" column ").append(i % this.boardSize)
.append(" has value ")
.append(fieldArray[i]).append(",");
}
}
}
}
}