Reputation: 1
Im trying to create a Wordle game in Java and i keep getting the error "illegal start of expression" can someone help me with this error and program? Confused on why the error keeps popping up and that is how it was given already.
import java.util.Scanner;
import java.util.Random;
public class Wordle_P3{
public static void main(String[] args) {
// The code for the word of the day is already in place.
final String WORD = getWordOfTheDay();
// Create Scanner Object
Scanner keyboard = new Scanner(System.in);
Random r = new Random();
// For loop that loops 6 times
for(int attempts = 0; attempts <= 6; attempts++){
// Have the user make a guess
System.out.println("Guess a five letter word.");
String guess = keyboard.nextLine();
// Make sure that the guess is five letters
int wordLength = guess.length();
while(wordLength != 5){
System.out.println("Not a five letter word.");
guess = keyboard.nextLine();
wordLength = guess.length();
}
// Checking for a win
String upperGuess = guess.toUpperCase();
if(guess.equals(WORD)){
System.out.println("Correct! You Won!");
return;
}
for(int i = 0; i < 5; i++){
char guessChar = upperGuess.charAt(i);
char feedback = '-';
for(int j = 0; j < 5; j++){
char wordChar = WORD.charAt(j);
if(wordChar == guessChar){
if(i == j)
feedback = guessChar;
else
feedback = guess.toLowerCase().charAt(i);
}
System.out.print(feedback);
System.out.println();
}
System.out.println("Sorry, you lost. Word was "+ WORD);
// Check each letter in guess and see if it is a miss, exct match, or close match
// for each letter in upperGuess
}
}
Random r = new Random();
return WORDS[r.nextInt(WORDS.length)];
private static final String[] WORDS = {
//the rest of the code is a bunch of random words that were given for the program
}
can someone help me with this error and program? Confused on why the error keeps popping up and that is how it was given already.
Upvotes: 0
Views: 978
Reputation: 9192
I believe the code:
Random r = new Random();
return WORDS[r.nextInt(WORDS.length)];
belongs within the getWordOfTheDay()
method which you simply don't provide, for example:
private String getWordOfTheDay() {
Random r = new Random();
return WORDS[r.nextInt(WORDS.length)];
}
It shouldn't be where is resides now.
The WORDS[] array looks to be a Class constant which is declared and filled within the class members area:
public class Wordle_P3 {
private final String[] WORDS = {"quake", "qualm", "quark", "quart", "quash", "quasi", "queen", "queer", "quell",
"query", "quest", "queue", "quick", "quiet", "quill", "quilt", "quirk", "quite", "quota", "quote", "quoth",
"rabbi", "rabid", "racer", "radar", "radii", "radio", "rainy", "raise", "rajah", "rally", "ralph", "ramen",
"ranch", "randy", "range", "rapid", "rarer", "raspy"};
public static void main(String[] args) {
// .... game code ...
}
private String getWordOfTheDay() {
Random r = new Random();
return WORDS[r.nextInt(WORDS.length)];
}
}
In my opinion, the WORDS array should be filled from words list within a text file rather than hard-coded but, a few words for demo purposes, this should suffice.
Your allowing for 6 attempts to guess the randomly provided word but your for
loop is allowing for 7 attempts:
for(int attempts = 0; attempts <= 6; attempts++) {
Iteration Value: 0 1 2 3 4 5 6
Number of iterations: 1 2 3 4 5 6 7
The attempts <= 6
should be attempts < 6
. Remove the =
from <=
.
Here is a runnable example of how this can work. Be sure to read all the comments in code:
public class WordleGameDemo {
// Create Scanner Object
private final java.util.Scanner keyboard = new java.util.Scanner(System.in);
// System's relative newLine character sequence:
private final String ls = System.lineSeparator();
public static void main(String[] args) {
/* App started this way to avoid the need for
statics unless we realy want them: */
new WordleGameDemo().startApp(args);
}
private void startApp(String[] args) {
// Randomly select a Word:
String word = getWordOfTheDay().toUpperCase();
// Get the selected word length:
int wordLength = word.length();
// Inform User about the Game:
String about = "The Wordle Game" + ls + "===============" + ls + ls
+ "You are displayed a Square Bracketed sequence of proposed" + ls
+ "characters which make up a word that is randomly selected." + ls
+ "You will be allowed six attempts to guess what the word" + ls
+ "is. Letters shown in square brackets ( [A] ) are an exact" + ls
+ "match and location. Letters with a hyphen on either side" + ls
+ "( [-A-] ) are in the randomly selected word but in the " + ls
+ "wrong place. Square Bracketed locations with just a hyphen" + ls
+ "in them ( [-] ) means there is no letter match at all." + ls
+ "Enter 'q' at any time to quit." + ls;
System.out.println(about);
// Display the number of characters within the randomly selected word:
System.out.print("Guess The Word: ");
System.out.println(String.join("", java.util.Collections.nCopies(wordLength, "[-]")) + ls);
// Declare a winner flag and initialize it to boolean false:
boolean winner = false;
// For loop that loops 6 times so that 6 attampts to solve is allowed:
for (int attempts = 0; attempts < 6; attempts++) {
// Have the user make a guess (contains valildation):
String guess = "";
while (guess.isEmpty()) {
System.out.print("Attempt #" + (attempts + 1)
+ ": Guess a " + wordLength + " letter word: -> ");
/* Get User input and set the result to uppercase and
trim off any leading/trailing whitespaces if any): */
guess = keyboard.nextLine().toUpperCase().trim();
// If 'q' is supplied then quit!
if (guess.equalsIgnoreCase("q")) {
System.out.println("Quiting - Bye Bye!");
return; // Returning from here will ultimately end the application:
}
/* If nothing was enterd or the word supplied was not
the determined random word length then inform User
of an invalid entry and allow to try again: */
if (guess.isEmpty() || guess.length() != wordLength) {
System.out.println("Invalid Entry (" + guess + ")! Either the guess is blank"
+ ls + "or not a " + wordLength + " letter word! Try again..." + ls);
guess = "";
}
}
// Checking for a win:
if (guess.equals(word)) {
System.out.println("Correct! You Won!");
winner = true;
break;
}
StringBuilder sb = new StringBuilder("");
// Create a char[] array of the randomly selected word to guess:
char[] wordChars = word.toCharArray();
// Create a char[] array of the User's current supplied word:
char[] guessChars = guess.toCharArray();
// Iterate through each charaacter of the randomly selected Word:
for (int i = 0; i < wordChars.length; i++) {
/* Is the current character location in the guessed word the
same character as what is in the random word character at
the same location: */
if (guessChars[i] == wordChars[i]) {
// Yes...Create the appropriate Character Bracketing (ie: [A]):
sb.append("[").append(guessChars[i]).append("]");
}
/* Is the current character location in the guessed word an
actual character within the random word but in a different
location (the isInWord() method is used): */
else if (isInWord(wordChars, guessChars[i])) {
// Yes...Create the appropriate Character Bracketing (ie: [-A-]):
sb.append("[-").append(guessChars[i]).append("-]");
}
/* Otherwise the current character location in the guessed
word is not within the randomly selected word: */
else {
// Create the appropriate Character Bracketing (ie: [-]):
sb.append("[-]");
}
}
// Display results from last entry:
System.out.println(" " + sb.toString());
}
/* If all attempts have been made and the `winner` flag
is still false then inform User that he/she lost the
game: */
if (!winner) {
System.out.println("Sorry - You had six attempts but lost this game!");
}
}
/**
* Indicates via true or false whether the supplied character resides within
* the supplied char[] array:<br><br>
*
* @param wordChars (char[] Array)
* @param c (char)
* @return (boolean)
*/
private boolean isInWord(char[] wordChars, char c) {
for (int j = 0; j < wordChars.length; j++) {
if (c == wordChars[j]) { return true; }
}
return false;
}
/**
* Randomly selects the 'Word Of The Day' from a String[] array.<br><br>
*
* @return (String) The random word
*/
private String getWordOfTheDay() {
/* NOTE: These words (and a lot more of them) should be read
in from a text File! Only here for demo! See the commented
example code below to read this data from a text file as a
single string which can then be split into individual words:*/
// Five letter words:
String words = "aback abase abate abbey abbot abhor abide abled abode abort about "
+ "above abuse abyss acorn acrid actor acute adage adapt adept admin admit "
+ "adobe adopt adore adorn adult affix afire afoot afoul after again agape "
+ "agate agent agile aging aglow agony agree ahead aider aisle alarm album "
+ "alert algae alibi alien align alike alive allay alley allot allow alloy "
+ "aloft alone along aloof aloud alpha altar alter amass amaze amber amble "
+ "amend amiss amity among ample amply amuse angel anger angle angry angst "
+ "anime ankle annex annoy annul anode antic anvil aorta apart aphid aping "
+ "apnea apple apply apron aptly arbor ardor arena argue arise armor aroma "
+ "arose array arrow arson artsy ascot ashen aside askew assay asset atoll "
+ "atone attic audio audit augur aunty avail avert avian avoid await awake "
+ "award aware awash awful awoke axial axiom axion azure bacon badge badly "
+ "bagel baggy baker baler balmy banal banjo barge baron basal basic basil";
/*
// Read in Words data from a Text file ("words.txt"). Words are in
// the text file as a single string where each word is separated
// with a white-space:
try {
String words = new java.util.Scanner(
new java.io.File("MyWordsFile.txt")).useDelimiter("\\Z").next();
}
catch (FileNotFoundException ex) {
System.err.println(ex);
}
*/
if (words == null || words.isEmpty()) {
throw new RuntimeException(
"getWordOfTheDay() Method Error! Words String Is Null or Empty!");
}
String[] wordsArray = words.split("\\s+");
return wordsArray[new java.util.Random().nextInt(wordsArray.length)];
}
}
Upvotes: 0