How would you go about creating this program? You will implement a Jumble Crossw
ID: 3815308 • Letter: H
Question
How would you go about creating this program?
You will implement a Jumble Crossword puzzle program that allows the user to attempt to unscramble the words in the puzzle. Your program must be named JumbleCrossword.
Each puzzle will contain 10 words. To make it easier to program, each word will be displayed horizontally from left to right or displayed vertically from top to bottom. Each crossword puzzle will be stored internally as 15 rows and 15 columns of uppercase letters and spaces. However, when the puzzle is displayed there will be an extra space between each character in a row, but no space after the last character. This will make it easier to see the individual letters.
Information about the words for each game is provided in a text file, read at program startup. We're providing three files for the game, Computers.txt, NCState.txt, and VideoGames.txt, which contain words from the following categories: Computers, NC State, and Video Games, respectively. However, your program must work given any word search file that is properly formatted. The first line of each file contains the title for the game, e.g., "Computer Terms". Each of the remaining 10 lines contains the following items:
a single scrambled uppercase word to be guessed
the corresponding unscrambled uppercase word
the row in which the first letter of the word is to be displayed in the puzzle
the column in which the first letter of the word is to be displayed in the puzzle
an uppercase H or V which denotes whether the word is to be displayed Horizontally or Vertically
You may assume that each file is correctly formatted, contains 10 words, that there are no duplicate words, and that if two words overlap, the letter where they overlap will be the same.
The word file shall be specified as a command-line argument.
When the play begins, the instruction, "See how many of the 10 words you can unscramble!", is displayed followed by the title of the puzzle and the puzzle itself. The puzzle will contain the 10 scrambled words from the file provided on the command line.
The user should then be prompted to enter each of the 10 words contained in the puzzle:
Each time the user enters a correctly unscrambled word without regard to case, the title of the puzzle and the puzzle itself should be redisplayed with the scrambled word replaced by the unscrambled word. If the user enters an incorrect word, an error message should be output. If the user enters a word that was previously guessed (as correct), an error message should also be output. At the end, the program should output the number of correctly unscrambled words and the message, "Thanks for playing, have a nice day!".
Example Command-line Argument Usage
The word file shall be specified as a command-line argument. For example,
csc$ java JumbleCrossword Computers.txt
If there is not exactly one argument on the command line, then the following usage message shall be displayed and the program will immediately exit. For example,
csc$ java JumbleCrossword
Usage: java JumbleCrossword wordfilename
csc$ java JumbleCrossword Computers.txt NCState.txt
Usage: java JumbleCrossword wordfilename
If the text file corresponding to the category on the command line cannot be accessed, then the following error and usage messages shall be displayed and the program will immediately exit. For example,
csc$ java JumbleCrossword NotAGame.txt
NotAGame.txt (No such file or directory)
Usage: java JumbleCrossword wordfilename
Example Program Execution
Below is a sample run of the JumbleCrossword program:
csc$ java JumbleCrossword Computers.txt
See how many of the 10 words you can unscramble!
Computer Terms
N C O I
U U C U P
T B R
P R R G M A O
E H
M S
O E A
R R A A Y C
T S E T
B
Word 1: Icon
Computer Terms
I C O N
U U C U P
T B R
P R R G M A O
E H
M S
O E A
R R A A Y C
T S E T
B
Word 2: cup
Sorry, cup is not a puzzle word or has already been found!
Word 3: cpu
Computer Terms
I C O N
U U C P U
T B R
P R R G M A O
E H
M S
O E A
R R A A Y C
T S E T
B
Word 4: PROGRAM
Computer Terms
I C O N
U U C P U
T B R
P R O G R A M
E H
M S
O E A
R R A A Y C
T S E T
B
Word 5: bug
Computer Terms
I C O N
U B C P U
T U R
P R O G R A M
E H
M S
O E A
R R A A Y C
T S E T
B
Word 6: array
Computer Terms
I C O N
U B C P U
T U R
P R O G R A M
E H
M S
O E A
A R R A Y C
T S E T
B
Word 7: program
Sorry, program is not a puzzle word or has already been found!
Word 8: byte
Computer Terms
I C O N
U B C P U
T U R
P R O G R A M
E H
M S
O B A
A R R A Y C
T S E T
E
Word 9: TeST
Computer Terms
I C O N
U B C P U
T U R
P R O G R A M
E H
M S
O B A
A R R A Y C
T E S T
E
Word 10: Harc
Sorry, Harc is not a puzzle word or has already been found!
You unscrambled 7 of the 10 words!
Thanks for playing, have a nice day!
Your program will create and use an array of Word class objects. The Word class is provided for you in the file, Word.java. See the Word API for information about the Word constructor and methods. Do not change this file, but use it as is. Place it in the same directory as your JumbleCrossword.java file. You will need to compile both files.
IMPORTANT: Your program must contain and use the methods listed below. You must use these exact method headers in your program and the methods must function exactly as described in order for automated testing to work. In industry, it is common to be required to write methods to precisely defined specifications, and deviating from the specifications can break the larger system. Feel free to add other methods as you see fit.
The methods below require that you check the parameters and throw an exception if they are not valid. It is good practice to include a helpful/descriptive message when you throw an exception. For this project, it is required that (at a minimum) you include a message (via parameter to constructor) with each IllegalArgumentException you throw. Here is an example of how to do this:
if (rows < 1 || cols < 1) {
throw new IllegalArgumentException("Invalid number of rows or " +
"cols (parameter) when creating puzzle (createPuzzle)");
}
Required Methods
// Creates and returns a 2D char array with the given number of rows and columns.
// The characters for each scrambled word in the words array should be placed in the
// 2D array such that the first character of the word is in the element at
// the given row and column and the remaining characters are in the proper place
// depending on whether the word is to be displayed horizontally or vertically.
// All other characters in the 2D array must be a space character, ' '
// Throw an IllegalArgumentException if rows or cols is less than 1
public static char[][] createPuzzle(int rows, int cols, Word[] words) {
}
// Handles the play for the word search game
// Outputs the instruction for the game
// Repeatedly displays the puzzle and prompts the user to enter each
// of the 10 words.
// Each time the user enters a correct word, the puzzle is changed
// such that the scrambled word is replaced by the unscrambled word,
// and the puzzle is redisplayed.
// If the user enters an incorrect word, an error message is output.
// Outputs the number of correct words when the game is over
// Throw an IllegalArgumentException if the title is null
// Throw an IllegalArgumentException if the puzzle is "jagged", that is if every
// row does not contain the same number of elements.
public static void playGame(Scanner console, String title, Word[] words, char[][] puzzle) {
}
// Outputs the title of the puzzle followed by characters contained the 2D
// puzzle array
// Do not assume that the puzzle has a specific number of rows and columns!
// Throw an IllegalArgumentException if title is null
// Throw an IllegalArgumentException if the puzzle is "jagged", that is if
// every row does not contain the same number of elements.
public static void displayPuzzle(String title, char[][] puzzle) {
}
// If the guess (disregarding case) is in the words array and has NOT been
// found yet, the corresponding word object reference is returned
// Otherwise, null is returned
// Throw an IllegalArgumentException if guess is null
public static Word isPuzzleWord(String guess, Word[] words) {
}
// The word is set as found
// Each letter of the scrambled word in the puzzle is replaced
// with the appropriate letter of the unscrambled word
// Throw an IllegalArgumentException if the puzzle is "jagged", that is if
// every row does not contain the same number of elements.
public static void updatePuzzle(Word word, char[][] puzzle) {
}
Implementation
You must store the data from the file into an array of Word objects. Store the data in the array BEFORE interacting with the user. Here is some sample code that illustrates how to create and use an array of Word objects followed by the output produced by the code:
//Create Word array with room for 4 Word objects
Word[] words = new Word[4];
//Create and add 4 Word objects to the words array
words[0] = new Word("RUBHS", "BRUSH", 2, 6, true);
words[1] = new Word("APOS", "SOAP", 0, 2, false);
words[2] = new Word("OMBC","COMB", 3, 4, true);
words[3] = new Word("TNIOLO", "LOTION", 4, 2, true);
//Output each scrambled word, word, row, column, whether it is displayed horizontally, and whether it has been found
for (int i = 0; i < words.length; i++) {
System.out.println("Scrambled word: " + words[i].getScrambledWord() + " Word: " + words[i].getWord() +
" Row: " + words[i].getRow() + " Column: " + words[i].getCol() +
" Horizontal?: " + words[i].isHorizontal() + " Found?: " + words[i].isFound());
}
//Search for COMB and set it to be found
for (int i = 0; i < words.length; i++) {
if (words[i].getWord().equals("COMB")) {
words[i].setIsFound(true);
}
}
System.out.println();
//Output each scrambled word, word, row, column, whether it is displayed horizontally, and whether it has been found
for (int i = 0; i < words.length; i++) {
System.out.println("Scrambled word: " + words[i].getScrambledWord() + " Word: " + words[i].getWord() +
" Row: " + words[i].getRow() + " Column: " + words[i].getCol() +
" Horizontal?: " + words[i].isHorizontal() + " Found?: " + words[i].isFound());
}
Outputs:
Scrambled word: RUBHS Word: BRUSH Row: 2 Column: 6 Horizontal?: true Found?: false
Scrambled word: APOS Word: SOAP Row: 0 Column: 2 Horizontal?: false Found?: false
Scrambled word: OMBC Word: COMB Row: 3 Column: 4 Horizontal?: true Found?: false
Scrambled word: TNIOLO Word: LOTION Row: 4 Column: 2 Horizontal?: true Found?: false
Scrambled word: RUBHS Word: BRUSH Row: 2 Column: 6 Horizontal?: true Found?: false
Scrambled word: APOS Word: SOAP Row: 0 Column: 2 Horizontal?: false Found?: false
Scrambled word: OMBC Word: COMB Row: 3 Column: 4 Horizontal?: true Found?: true
Scrambled word: TNIOLO Word: LOTION Row: 4 Column: 2 Horizontal?: true Found?: false
Restrictions
Do NOT use throws clause(s) in the method headers of your program. Instead use try/catch blocks and respond appropriately as required by this document. See Appendix C of the textbook for more information on try/catch statements.
Your program must work for any correctly formatted word file.
Explanation / Answer
/**
*
*/
package com.chegg.test;
/**
* @author NAP0911
*
*/
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class Crossword {
public static class WordsInfo {
private String word;
private int rowFrom;
private int rowTo;
private int colFrom;
private int colTo;
WordsInfo(String word, int rowFrom, int colFrom, int rowTo, int colTo) {
this.word = word;
this.rowFrom = rowFrom;
this.rowTo = rowTo;
this.colFrom = colFrom;
this.colTo = colTo;
}
public String getWord() { return word; }
public int getRowFrom() { return rowFrom; }
public int getRowTo() { return rowTo; }
public int getColFrom() { return colFrom; }
public int getColTo() { return colTo; }
public String toString() {
String info = "[" + (char) (colFrom + 'A') + ", " +
String.format("%-2s", (rowFrom+1)) + "] -> [" +
(char)(colTo+'A') + ", " +
String.format("%-2s", (rowTo+1)) + "] : " +
word.toUpperCase();
return info;
}
public int compareTo(WordsInfo word2) {
return word.compareTo(word2.word);
}
}
private static int numLetters = 3;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
if( args.length < 2 ) {
System.err.println("Must input a dictionary AND puzzle" +
"file to read");
System.err.println("Usage: java WordSearch <dictionary> <puzzle>" +
"<minimum_number_of_letters>");
System.exit(1);
}
if( args.length == 3 ) {
numLetters = Integer.parseInt(args[2]);
}
ArrayList<String> dict = loadDict(args[0]);
char[][] grid = loadPuzzle(args[1]);
ArrayList<WordsInfo> solutions = findWords(grid, dict, numLetters);
printGrid(grid);
printSolutions(solutions, numLetters);
Runtime runtime = Runtime.getRuntime();
runtime.gc();
long endTime = System.currentTimeMillis();
System.out.println("Time taken: " + (endTime - startTime) +
" milliseconds");
System.out.println("Memory used: " +
((runtime.totalMemory() - runtime.freeMemory()) / 1024) +
" kB");
System.exit(0);
}
private static ArrayList<String> loadDict(String filename) {
ArrayList<String> dict = new ArrayList<String>();
try {
BufferedReader in = new BufferedReader(
new FileReader(filename));
String word;
while( (word = in.readLine()) != null ) {
dict.add(word);
}
} catch( IOException e ) {
System.err.println("A file error occurred: " + filename );
System.exit(1);
}
return dict;
}
public static char[][] loadPuzzle(String filename) {
char[][] grid = new char[0][0];
try {
BufferedReader in = new BufferedReader(
new FileReader(filename));
String line = in.readLine();
int rows = Integer.parseInt(line.split(" ")[0]);
int cols = Integer.parseInt(line.split(" ")[1]);
grid = new char[rows][cols];
int rowNum = 0;
int colNum = 0;
while( (line = in.readLine()) != null ) {
colNum = 0;
String[] letters = line.split(" ");
for( String s : letters ) {
grid[rowNum][colNum] =
Character.toLowerCase( s.charAt(0) );
colNum++;
}
rowNum++;
}
} catch( IOException e ) {
System.err.println("A file error occurred: " + filename );
System.exit(1);
}
return grid;
}
private static ArrayList<WordsInfo> findWords(char[][] grid,
ArrayList<String> dict,
int numLetters) {
int cols = grid[0].length;
int rows = grid.length;
ArrayList<WordsInfo> results = new ArrayList<WordsInfo>();
for( int i = 0; i < rows; i++ ) {
for( int j = 0; j < cols; j++ ) {
if(i - (numLetters-1) >= 0) {
results.addAll(moveN(grid, dict, i, j));
}
if(j - (numLetters-1) >= 0) {
results.addAll(moveW(grid, dict, i, j));
}
if( j - (numLetters-1) >= 0 && i - (numLetters-1) > 0) {
results.addAll(moveNW(grid, dict, i, j));
}
if( i - (numLetters-1) >= 0 && j + (numLetters-1) < cols) {
results.addAll(moveNE(grid, dict, i, j, rows, cols));
}
}
}
return results;
}
private static ArrayList<WordsInfo> moveN(char[][] grid,
ArrayList<String> dict,
int row, int col) {
ArrayList<WordsInfo> results = new ArrayList<WordsInfo>();
StringBuilder word = new StringBuilder();
for( int i = row; i >= 0; i-- ) {
word.append(grid[i][col]);
if(word.length() >= numLetters) {
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(),
row, col, i, col));
}
word.reverse();
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(),
i, col, row, col));
}
word.reverse();
}
}
return results;
}
private static ArrayList<WordsInfo> moveW(char[][] grid,
ArrayList<String> dict,
int row, int col ) {
ArrayList<WordsInfo> results = new ArrayList<WordsInfo>();
StringBuilder word = new StringBuilder();
for( int j = col; j >= 0; j-- ) {
word.append(grid[row][j]);
if(word.length() >= numLetters) {
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(),
row, col, row, j));
}
word.reverse();
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(),
row, j, row, col));
}
word.reverse();
}
}
return results;
}
private static ArrayList<WordsInfo> moveNW(char[][] grid,
ArrayList<String> dict,
int row, int col) {
ArrayList<WordsInfo> results = new ArrayList<WordsInfo>();
StringBuilder word = new StringBuilder();
for( int i = row, j = col; i >= 0 && j >= 0; i--, j-- ) {
word.append(grid[i][j]);
if(word.length() >= numLetters) {
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(), row, col, i, j));
}
word.reverse();
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(), i, j, row, col));
}
word.reverse();
}
}
return results;
}
private static ArrayList<WordsInfo> moveNE(char[][] grid,
ArrayList<String> dict,
int row, int col,
int numRows, int numCols) {
ArrayList<WordsInfo> results = new ArrayList<WordsInfo>();
StringBuilder word = new StringBuilder();
for( int i = row, j = col; i >= 0 && j < numCols; i--, j++) {
word.append(grid[i][j]);
if(word.length() >= numLetters) {
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(), row, col, i, j));
}
word.reverse();
if(Collections.binarySearch(dict, word.toString()) >= 0) {
results.add(new WordsInfo(word.toString(), i, j, row, col));
}
word.reverse();
}
}
return results;
}
public static void printGrid(char[][] grid) {
System.out.print(" ");
for( int i = 0; i < grid.length; i++ ) {
System.out.print((char) ('A' + i) + " ");
}
System.out.println();
System.out.print(" ");
for( int i = 0; i < grid.length; i ++ ) {
System.out.print("--");
}
System.out.println();
int rowNum = 1;
for( char[] row : grid ) {
System.out.printf("%02d |", rowNum);
for( char c : row ) {
System.out.print(Character.toUpperCase(c) + " ");
}
System.out.println();
rowNum++;
}
System.out.println();
}
public static void printSolutions(ArrayList<WordsInfo> words,
int numLetters) {
Collections.sort(words, new Comparator<WordsInfo>() {
@Override
public int compare(WordsInfo word1, WordsInfo word2) {
return word1.compareTo(word2);
}
});
System.out.println("Found " + words.size() + " words with " +
numLetters + " letters or more");
for(WordsInfo w: words) {
System.out.println(w.toString());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.