Arrays
© luv2code LLC
Arrays
• An array is a data structure that holds multiple elements of the same typ
• Array of Strings
“Red” “Green” “Blue” “Yellow”
• Array of ints
100 76 89
www.luv2code.com © luv2code LLC
Arrays - Use Cases
• Sorting, searching and performing calculations
• Accessing data directly with an inde
• In more complex applications
• Buffering dat
a
• Managing multiple data sources, both input and outpu
• …
www.luv2code.com © luv2code LLC
Arrays - Initialization We’ll cover
growable data structures
later in the course
• Arrays are xed size … don’t grow over tim
fi
e
• Specify the size/contents during initialization One approach for
initializing the array
// initialize the arra
String[] colors = { "Red", "Green", "Blue", "Yellow" };
www.luv2code.com © luv2code LLC
Accessing Elements in an Array
• Arrays are zero-based. The rst element is at position 0.
fi
0 1 2 3
“Red” “Green” “Blue” “Yellow”
Contents of the array
Re
Gree
// initialize the arra
Blu
y
String[] colors = { "Red", "Green", "Blue", "Yellow" } Yellow
// display contents of the arra
System.out.println("Contents of the array:") Remember, arrays are 0-based
System.out.println(colors[0]);
The first element is at index/position 0
System.out.println(colors[1])
;
System.out.println(colors[2])
;
System.out.println(colors[3])
Index to an element in the array
;
using square brackets: [ …]
www.luv2code.com © luv2code LLC
Length of the array
• To nd the length, access the .length attribute
fi
0 1 2 3
“Red” “Green” “Blue” “Yellow”
// initialize the arra y
String[] colors = { "Red", "Green", "Blue", "Yellow" } Length of the array:
// display length of the array
System.out.println("Length of the array: " + colors.length);
Remember,
arrays are 0-based
Length attribute
www.luv2code.com © luv2code LLC
Pulling It All Together
public class ArrayDemo
public static void main(String[] args)
// initialize the arra
String[] colors = { "Red", "Green", "Blue", "Yellow" }
// display contents of the arra Contents of the array
System.out.println("Contents of the array:") Re
System.out.println(colors[0]) Gree
System.out.println(colors[1]) Blu
System.out.println(colors[2])
Yello
System.out.println(colors[3])
System.out.println() Length of the array: 4
;
// display length of the arra
y
System.out.println("Length of the array: " + colors.length)
www.luv2code.com © luv2code LLC
Looping Through an Array - Version 1
public class ArrayDemo
public static void main(String[] args)
// initialize the arra
String[] colors = { "Red", "Green", "Blue", "Yellow" }
Remember,
arrays are 0-based // loop through the array - version
System.out.println("Looping through the array:")
for (int i=0; i < colors.length; i++) Length attribute
System.out.println(colors[i])
Looping through the array
Index to an element in the array Re
}
using square brackets: [ …] Gree
Blu
Yellow
www.luv2code.com © luv2code LLC
Looping Through an Array - Version 2
public class ArrayDemo
public static void main(String[] args)
// initialize the arra
String[] colors = { "Red", "Green", "Blue", "Yellow" }
enhanced // loop param
typeloop through the array - array
version
for loop
can give any name
System.out.println("Using enhanced for loop:”)
for (String temp : colors)
System.out.println(temp)
Using enhanced for loop
}
Re
No need to manually index into the array … Gree
}
Blu
Handled for you behind the scenes with the Yello
enhanced for loop
www.luv2code.com © luv2code LLC
Arrays Initialization
© luv2code LLC
Arrays - Initialization
• Previously, we speci ed the contents during initialization
fi
// initialize the arra
String[] colors = { "Red", "Green", "Blue", "Yellow" };
• What if we wanted to specify the size of the array … but add data later??
• For example, with an array of student grade
• We know a student will have three grades this semeste
• But, we will enter the grades later …
www.luv2code.com © luv2code LLC
Arrays - Initialization
• For student grades, we will have an array of doubles
100.0 76.7 89.0
• Let’s start with an array of doubles, size of 3
www.luv2code.com © luv2code LLC
Arrays - Initialization
• Let’s start with an array of doubles, size of 3
… … …
0 1 2
// initialize the arra
double[] grades = new double[3];
Create a new array Remember, arrays are 0-based
Size of the array
The number of elements The first element is at index/position 0
www.luv2code.com © luv2code LLC
Arrays - Initialization
• Since no initial values given, for double … will default to 0.0
// initialize the arra
double[] grades = new double[3];
0 1 2
double, default to 0.0 0.0 0.0 0.0
www.luv2code.com © luv2code LLC
Assigning Values
• We can assign values to the array elements
// initialize the arra
double[] grades = new double[3]
// assign student grade
grades[0] = 100.0 ;
0 1 2
grades[1] = 76.7
;
grades[2] = 89.0 100.0 76.7 89.0
;
www.luv2code.com © luv2code LLC
Pulling It All Together
public class StudentGradesDemo
public static void main(String[] args)
// initialize the arra
double[] grades = new double[3]
// assign student grade
grades[0] = 100.0
grades[1] = 76.7;
grades[2] = 89.0
;
for (double temp : grades) 100.
System.out.println(temp) 76.
89.0
}
www.luv2code.com © luv2code LLC
Read Input From User
• Let’s prompt the user for how many grade How many grades will you enter? 4
• Initialize the array based on the number of grade Enter grade number 1: 100.0
Enter grade number 2: 76.7
Enter grade number 3: 94.2
• Read each grade and assign to an array elemen Enter grade number 4: 88.4
• Print out the array elements 100.
76.
94.
88.4
www.luv2code.com © luv2code LLC
Read Input From User
// prompt the user for how many grade
Scanner scanner = new Scanner(System.in)
System.out.print("How many grades will you enter? ")
int numGrades = scanner.nextInt()
How many grades will you enter? 4
System.out.println()
Enter grade number 1: 100.0
// initialize the array based on the number of grade
Enter grade number 2: 76.7
double[] userInputGrades = new double[numGrades]
Enter grade number 3: 94.2
Enter grade number 4: 88.4
// read each grade and assign to an array elemen
for (int i=0; i < userInputGrades.length; i++)
100.
System.out.print("Enter grade number " + (i+1) + ": ")
76.
userInputGrades[i] = scanner.nextDouble()
94.
88.4
}
System.out.println()
;
// print out the array element
s
for (double temp : userInputGrades)
{
System.out.println(temp)
;
scanner.close();
www.luv2code.com © luv2code LLC
Passing Arrays into Methods
© luv2code LLC
Computing Grade Average
• We currently have an array of grades
• Let’s compute the average grade
www.luv2code.com © luv2code LLC
Computing Grade Average
• De ne a new method and pass in an array
fi
Input parameter can have any name.
Return type Input parameter Must use exact same type: double[ ]
private static double computeGradeAverage(double[] userInputGrades)
// compute the sum of the grades
// compute the grade average, based on length of the arra
www.luv2code.com © luv2code LLC
Computing Grade Average
Return type Input parameter
private static double computeGradeAverage(double[] userInputGrades)
double sum = 0.0
// compute the sum of the grades
for (double temp : userInputGrades)
sum += temp
;
// compute the grade average, based on length of the array
double average = sum / userInputGrades.length
return average;
}
www.luv2code.com © luv2code LLC
Pull It All Together
// prompt the user for how many grade
..
.
// initialize the array based on the number of grade
double[] userInputGrades = new double[numGrades]
// read each grade and assign to an array elemen
for (int i=0; i < userInputGrades.length; i++)
System.out.print("Enter grade number " + (i+1) + ": ")
userInputGrades[i] = scanner.nextDouble()
private static double computeGradeAverage(double[] userInputGrades)
.. double sum = 0.0
double gradeAverage = computeGradeAverage(userInputGrades) // compute the sum of the grade
for (double temp : userInputGrades)
System.out.println("Grade average: " + gradeAverage) sum += temp
scanner.close();
// compute the grade average, based on length of the arra
double average = sum / userInputGrades.length
return average
www.luv2code.com © luv2code LLC
Returning Arrays from Methods
© luv2code LLC
Refactor
• Let’s refactor our app to return an array from a metho
• When we prompt a user for num grades and array content
• Extract this code to a separate metho
How many grades will you enter? 4
• Return the array from this method
Enter grade number 1: 100.0
Enter grade number 2: 76.7
Enter grade number 3: 94.2
Enter grade number 4: 88.4
www.luv2code.com © luv2code LLC
Returning Array from Method
Return type
private static double[] readUserInputGrades()
// prompt the user for how many grade
Scanner scanner = new Scanner(System.in)
System.out.print("How many grades will you enter? ")
How many grades will you enter? 4
int numGrades = scanner.nextInt()
System.out.println() Enter grade number 1: 100.0
;
// initialize the array based on the number of grade Enter grade number 2: 76.7
double[] userInputGrades = new double[numGrades] Enter grade number 3: 94.2
Enter grade number 4: 88.4
// read each grade and assign to an array elemen
for (int i=0; i < userInputGrades.length; i++)
System.out.print("Enter grade number " + (i+1) + ": ")
userInputGrades[i] = scanner.nextDouble()
scanner.close()
;
return userInputGrades Return the array
;
www.luv2code.com © luv2code LLC
Pull It All Together
public static void main(String[] args)
double[] userInputGrades = readUserInputGrades()
.. private static double[] readUserInputGrades()
double gradeAverage = computeGradeAverage(userInputGrades) // prompt the user for how many grade
Scanner scanner = new Scanner(System.in)
System.out.println("Grade average: " + gradeAverage) System.out.print("How many grades will you enter? ")
int numGrades = scanner.nextInt()
}
System.out.println()
// initialize the array based on the number of grade
double[] userInputGrades = new double[numGrades]
// read each grade and assign to an array elemen
for (int i=0; i < userInputGrades.length; i++)
System.out.print("Enter grade number " + (i+1) + ": ")
userInputGrades[i] = scanner.nextDouble()
scanner.close()
return userInputGrades
www.luv2code.com © luv2code LLC
Array Utilities: Filling an Array
© luv2code LLC
Array Utility Methods
• The Arrays class has a number of utility methods for array
• lling, sorting and searching (we’ll cover these in the next set of videos)
fi
• Also, other utility methods availabl
• array copying, conversions and comparisons
Use your Java version
• You can research these onlin
e
• keyword search: arrays javadoc java <version>
www.luv2code.com © luv2code LLC
Arrays - Initialization
• Remember, since no initial values given, for double … will default to 0.0
// initialize the arra
double[] grades = new double[3];
0 1 2
double, default to 0.0 0.0 0.0 0.0
How can I fill an array with a value?
www.luv2code.com © luv2code LLC
Filling an Array
• We can use the method: Arrays.fill(theArray, theValue)
// initialize the arra
double[] grades = new double[3] 0 1 2
// fill the array
75.0 75.0 75.0
Arrays.fill(grades, 75.0)
www.luv2code.com © luv2code LLC
Read Input From User
• Prompt the user for size of arra What size array do you want? 4
What number do you want to fill the array with? 30
• Prompt user on number to ll array wit
fi
h
• Initialize the array based on the siz 3
• Fill the array with given number 30
• Print out the array elements
www.luv2code.com © luv2code LLC
Read Input From User
// prompt the user for size of the arra
Scanner scanner = new Scanner(System.in)
System.out.print("What size array do you want? ")
int size = scanner.nextInt()
What size array do you want?
What number do you want to fill the array with? 3
System.out.print("What number do you want to fill the array with? ")
int theNum = scanner.nextInt() 3
// initialize the arra 3
int[] myDataArray = new int[size] 30
// fill the arra
y
Arrays.fill(myDataArray, theNum)
;
System.out.println()
;
// display contents of the arra
y
for (int temp : myDataArray)
{
System.out.println(temp)
;
scanner.close();
www.luv2code.com © luv2code LLC
Array Utilities: Sorting an Array
© luv2code LLC
Sorting an Array
• We can use the method: Arrays.sort(theArray)
0 1 2
// initialize the arra 61 4 25
int[] myData = { 61, 4, 25 }
// sort the arra
y
Arrays.sort(myData)
;
0 1 2
4 25 61
www.luv2code.com © luv2code LLC
Read Input From User
• Prompt the user for size of arra What size array do you want?
Enter number 1: 6
Enter number 2:
• Prompt user for the array content
Enter number 3: 2
• Initialize the array based on the siz BEFORE sorting
Print out the array elements BEFORE sorting
• 2
AFTER sorting
• Sort the array
• Print out the array elements AFTER sorting 61
www.luv2code.com © luv2code LLC
Read Input From User
// prompt the user for how size of arra
Scanner scanner = new Scanner(System.in)
System.out.print("What size array do you want? ") What size array do you want? 3
int size = scanner.nextInt()
Enter number 1: 61
// initialize the array based on the siz Enter number 2: 4
int[] myDataArray = new int[size] Enter number 3: 25
// read each number and assign to an array elemen
BEFORE sorting
for (int i=0; i < myDataArray.length; i++)
System.out.print("Enter number " + (i+1) + ": ") 6
myDataArray[i] = scanner.nextInt()
2
}
System.out.println()
;
AFTER sorting
// print out the array element
s
System.out.println("BEFORE sorting:")
displayData(myDataArray) 2
61
System.out.println()
;
Arrays.sort(myDataArray)
;
System.out.println("AFTER sorting:") private static void displayData(int[] myDataArray)
displayData(myDataArray) for (int temp : myDataArray)
System.out.println(temp)
scanner.close(); }
www.luv2code.com © luv2code LLC
Array Utilities: Searching an Array
© luv2code LLC
Searching an Array
• We can use the method: Arrays.binarySearch(theArray, theSearchKey)
• Returns the array index where theSearchKey was found
Specified in the
Java documentation
for this method
• Note: The array must be sorted prior to calling this method
• If not sorted, then the results are unde ned and unpredictable
fi
• May get incorrect results or may not nd the value even if it exists … gasp!
fi
• Best practice: Sort the array before calling the Arrays.binarySearch(…) method
www.luv2code.com © luv2code LLC
Searching an Array - Example
// initialize the arra
int[] myDataArray = { 61, 4, 25 }
int searchKey = 4
// sort array firs Method returns the array index
t
Arrays.sort(myDataArray) where searchKey was found
// search the arra
y
int result = Arrays.binarySearch(myDataArray, searchKey)
boolean found = (result >= 0) If array index >= 0 then we found it
;
else, we didn’t find it
System.out.println("Found: " + found)
www.luv2code.com © luv2code LLC
Read Input From User
• Prompt the user for size of arra What size array do you want? 3
Enter number 1: 6
• Prompt user for the array content Enter number 2:
Enter number 3:
4
25
• Initialize the array based on the siz What number do you want to search for? 4
Found: tru
Prompt user for the search key
• We found the number: 4
• Sort the array
• Search the arra
y
• Print out the results
www.luv2code.com © luv2code LLC
Read Input From User
// prompt the user for how size of arra
Scanner scanner = new Scanner(System.in)
System.out.print("What size array do you want? ")
int size = scanner.nextInt()
// initialize the array based on the siz
int[] myDataArray = new int[size]
What size array do you want?
// read each number and assign to an array elemen
Enter number 1: 6
for (int i=0; i < myDataArray.length; i++)
System.out.print("Enter number " + (i+1) + ": “)
Enter number 2:
myDataArray[i] = scanner.nextInt()
Enter number 3: 2
}
System.out.println()
;
System.out.print("What number do you want to search for? ") What number do you want to search for?
int searchKey = scanner.nextInt()
;
System.out.println()
Found: tru
;
// sort array firs
We found the number: 4
t
Arrays.sort(myDataArray)
;
// search the arra
y
int result = Arrays.binarySearch(myDataArray, searchKey) ;
boolean found = (result >= 0)
;
System.out.println("Found: " + found)
;
if (found)
{
System.out.println("We found the number: " + searchKey)
;
else
{
System.out.println("We did not find the number: " + searchKey)
;
scanner.close();
www.luv2code.com © luv2code LLC
Two-Dimensional (2D) Arrays
© luv2code LLC
2D Arrays
• Represent a grid of data
• Classic example is a multiplication table
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
www.luv2code.com © luv2code LLC
2D Arrays - Use Cases
• Multiplication tables
• Matrix calculations
• Grid-based game boards
• Seating charts
• Scheduling and timetables
• Image processing
• Route navigation
• others …
www.luv2code.com © luv2code LLC
Multidimensional Arrays
• Java also supports multidimensional arrays: 2D, 3D, …
• 3D arrays are useful for terrain mapping, robotics, gaming etc …
• In general, you will commonly see 1D and 2D arrays
www.luv2code.com © luv2code LLC
2D Arrays - Initialization
• Specify the size/contents during initialization
// initialize the array
int numRows = 2;
int numCols = 3;
int[][] tableDemo = new int[numRows][numCols];
0 1 2
0 0 0 0
1 0 0 0
www.luv2code.com © luv2code LLC
2D Arrays - Initialization
• Specify the size/contents during initialization
// initialize the array Row 0
int[][] tableDemo = {
{90, 85, 100, 93},
{60, 70, 80, 87}
};
Row 1
0 1 2 3
0 90 85 100 93
1 60 70 80 87
www.luv2code.com © luv2code LLC
Accessing Elements in a 2D Array
Remember,
• Index into the array using: [theRow][theCol] arrays are 0-based
// initialize the array 0 1 2 3
int[][] tableDemo = {
{90, 85, 100, 93}, 0 90 85 100 93
{60, 70, 80, 87}
}; 1 60 70 80 87
System.out.println(tableDemo[0][2]);
System.out.println(tableDemo[1][3]);
100
87
Row Col
www.luv2code.com © luv2code LLC
Read Input From User
• Prompt the user for number of rows and columns
How many rows? 4
How many columns? 5
• Initialize the array based on the rows and columns
1 2 3 4 5
• Compute multiplication table values 2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
• Print out the results
www.luv2code.com © luv2code LLC
Read Input From User
// Prompt the user for number of rows and columns
Scanner scanner = new Scanner(System.in);
System.out.print("How many rows? ");
int numRows = scanner.nextInt();
System.out.print("How many columns? ");
int numCols = scanner.nextInt(); How many rows? 4
// Initialize the array based on the rows and columns
How many columns? 5
int[][] table = new int[numRows][numCols];
// compute multiplication table values 1 2 3 4 5
for (int row=0; row < numRows; row++) {
2 4 6 8 10
for (int col=0; col < numCols; col++) { 3 6 9 12 15
// use (row+1) to give values 1 to (numRows)
// similar thing for (col+1) 4 8 12 16 20
table[row][col] = (row+1) * (col+1);
}
}
System.out.println();
// print out the results
for (int row=0; row < numRows; row++) {
for (int col=0; col < numCols; col++) {
\t: tab character
System.out.print(table[row][col] + "\t"); for alignment
}
System.out.println();
}
www.luv2code.com © luv2code LLC
Number Guessing Game
© luv2code LLC
Number Guessing Game
• Let’s have some fun and create a number guessing game!
• The app will create a random number
• Users will have 3 attempts to guess the number
www.luv2code.com © luv2code LLC
Number Guessing Game - Example
NUMBER GUESSING GAME
NUMBER GUESSING GAME You have 3 attempts.
You have 3 attempts.
Guess a number between 1 and 5: 1
Guess a number between 1 and 5: 2 Sorry, your guess is incorrect.
Sorry, your guess is incorrect. You have 2 attempt(s) left.
You have 2 attempt(s) left.
Guess a number between 1 and 5: 2
Guess a number between 1 and 5: 4 Sorry, your guess is incorrect.
Sorry, your guess is incorrect. You have 1 attempt(s) left.
You have 1 attempt(s) left.
Guess a number between 1 and 5: 3
Guess a number between 1 and 5: 5 Sorry, your guess is incorrect.
Success!!! You guessed the secret number: 5 You have 0 attempt(s) left.
You did not win. The secret number was: 4
Success!!!
Failure
www.luv2code.com © luv2code LLC
Development Process
• Initialize the game NUMBER GUESSING GAME
You have 3 attempts.
• Set the upper bound number and maximum number of attempts Guess a number between 1 and 5: 2
Sorry, your guess is incorrect.
You have 2 attempt(s) left.
• Generate a random secret number within the upper bound Guess a number between 1 and 5: 4
Sorry, your guess is incorrect.
• Game Loop You have 1 attempt(s) left.
Guess a number between 1 and 5: 5
Success!!! You guessed the secret number: 5
• For each attempt
• Prompt the player to guess a number
• If the guess is correct, print a success message and end the game
• If the guess is incorrect, print feedback with number of remaining attempts
• End Game Check
• If all attempts are used without a correct guess, reveal the secret number
www.luv2code.com © luv2code LLC
Game Development NUMBER GUESSING GAME
You have 3 attempts.
// Initialize the game
Guess a number between 1 and 5: 2
int upperBound = 5; Sorry, your guess is incorrect.
random.nextInt(5) You have 2 attempt(s) left.
// compute a random number between 1 and the upperBound
Random random = new Random();
Guess a number between 1 and 5: 4
int secretNumber = random.nextInt(upperBound) + 1; returns number: 0 to 4
Sorry, your guess is incorrect.
int maxAttempts = 3; You have 1 attempt(s) left.
We add +1 to make it: 1 to 5
System.out.println("NUMBER GUESSING GAME");
System.out.println("You have " + maxAttempts + " attempts."); Guess a number between 1 and 5: 5
System.out.println(); Success!!! You guessed the secret number: 5
Scanner scanner = new Scanner(System.in);
Success!!!
boolean won = false;
NUMBER GUESSING GAME
// Game Loop
for (int i=maxAttempts; i > 0; i--) { Loop countdown You have 3 attempts.
// prompt the user
System.out.print("Guess a number between 1 and " + upperBound + ": "); Failure Guess a number between 1 and 5: 1
Sorry, your guess is incorrect.
int theGuess = scanner.nextInt();
You have 2 attempt(s) left.
won = (theGuess == secretNumber); Check to see if the user won
Guess a number between 1 and 5: 2
if (won) {
System.out.println("Success!!! You guessed the secret number: " + secretNumber);
Sorry, your guess is incorrect.
break; You have 1 attempt(s) left.
}
else { Remember, break, Guess a number between 1 and 5: 3
System.out.println("Sorry, your guess is incorrect.");
System.out.println("You have " + (i - 1) + " attempt(s) left.");
will exit out of the current loop Sorry, your guess is incorrect.
System.out.println(); You have 0 attempt(s) left.
}
} You did not win. The secret number was: 4
// End Game Check
if (!won) {
If they didn’t win,
System.out.println("You did not win. The secret number was: " + secretNumber); then reveal
} the secret number
www.luv2code.com © luv2code LLC
Word Quest Game
© luv2code LLC
Word Quest Game
• Let’s develop a word quest game!
• The app will select a random word
• Users will guess the characters for the word
• Users will have 10 attempts to guess all of the characters
• Attempts are only reduced for wrong guesses
• No change for correct guesses
www.luv2code.com © luv2code LLC
Welcome to Word Quest!
Current word: ______
Guess a letter: n
Good job! You found a match!
Guess a letter: a
Attempts remaining: 9
Incorrect!
Attempts remaining: 9
Current word: __IEN_
Current word: ______
Guess a letter: F
Good job! You found a match!
Guess a letter: e
Attempts remaining: 9
Good job! You found a match!
Attempts remaining: 9
Current word: F_IEN_
Current word: ___E__
Guess a letter: R
Good job! You found a match!
Guess a letter: i
Attempts remaining: 9
Good job! You found a match!
Attempts remaining: 9
Current word: FRIEN_
Current word: __IE__ Success!!!
Guess a letter: D
Good job! You found a match!
Attempts remaining: 9
Success!!! You've revealed the word: FRIEND
www.luv2code.com © luv2code LLC
Development Process Welcome to Word Quest!
Current word: ______
Guess a letter: a
• Initialize the game Incorrect!
Attempts remaining: 9
• Get a random word from an array of words
Current word: ______
• Create a game board with underscores to represent unrevealed letters Guess a letter: e
Good job! You found a match!
• Game Loop Attempts remaining: 9
Current word: ___E__
• While we have more attempts left and the word is not fully revealed
Guess a letter: i
• Prompt the player to guess a letter Good job! You found a match!
Attempts remaining: 9
• If the guess is correct, print a success message and display updated word
Current word: __IE__
• If the guess is incorrect, print feedback with number of remaining attempts
• End Game Check
• If all attempts are used without a revealing all of the letters, reveal the secret word
• If the user revealed all of the letters, print a success message
www.luv2code.com © luv2code LLC
Game Development - Part 1
// Define the secret word and maximum allowed attempts
String secretWord = getRandomWord(); private static String getRandomWord() {
int maxAttempts = 10; String[] words = {"Java", "Airplane", "Friend"};
// Create a game board with underscores to represent unrevealed letters Random random = new Random();
char[] gameBoard = new char[secretWord.length()]; int index = random.nextInt(words.length);
// Flag to check if the word has been fully revealed String theWord = words[index];
boolean wordNotRevealed = true;
return theWord.toUpperCase();
// Initialize game board with underscores to represent missing letters }
for (int i = 0; i < gameBoard.length; i++) {
gameBoard[i] = '_';
}
We’ll refactor this later
// Scanner to read player input
Scanner scanner = new Scanner(System.in); Arrays.fill(…)
System.out.println("Welcome to Word Quest!");
www.luv2code.com © luv2code LLC
Game Development - Part 2
Guess a letter: a
Incorrect!
Attempts remaining: 9
Current word: ______
Guess a letter: e
Good job! You found a match!
Attempts remaining: 9
Current word: ___E__
// Define the secret word and maximum allowed attempts
String secretWord = getRandomWord();
int maxAttempts = 10; // Main game loop: runs while there are attempts left and the word is not fully revealed
while (maxAttempts > 0 && wordNotRevealed) {
// Create a game board with underscores to represent unrevealed letters System.out.print("Current word: ");
char[] gameBoard = new char[secretWord.length()]; System.out.println(gameBoard);
// Flag to check if the word has been fully revealed System.out.println();
boolean wordNotRevealed = true; System.out.print("Guess a letter: ");
// Initialize game board with underscores to represent missing letters // Read the user's input, take the first character, and convert it to uppercase
for (int i = 0; i < gameBoard.length; i++) { String userInput = scanner.next().toUpperCase();
gameBoard[i] = '_'; char guess = userInput.charAt(0);
}
// Track if the guess was correct
// Scanner to read player input boolean isGuessCorrect = false;
Scanner scanner = new Scanner(System.in);
// Loop through each letter in the secret word to check if it matches the guess
System.out.println("Welcome to Word Quest!"); for (int i = 0; i < secretWord.length(); i++) {
if (secretWord.charAt(i) == guess) {
// Reveal the correctly guessed letter on the game board
gameBoard[i] = guess;
isGuessCorrect = true;
} Guess a letter: a
} Incorrect!
Attempts remaining: 9
Current word: ______
// Update game status based on the guess
if (isGuessCorrect) { Guess a letter: e
Good job! You found a match!
System.out.println("Good job! You found a match!"); Attempts remaining: 9
private static boolean containsUnderscore(char[] gameBoard) {
for (char c : gameBoard) { Current word: ___E__
// Check if there are still unrevealed letters
if (c == '_') {
wordNotRevealed = containsUnderscore(gameBoard);
return true;
} else {
}
System.out.println("Incorrect!");
}
maxAttempts--; // Decrement attempts for an incorrect guess
return false;
}
}
// Display remaining attempts after each guess
System.out.println("Attempts remaining: " + maxAttempts);
System.out.println();
}
www.luv2code.com © luv2code LLC
Game Development - Part 3
// End of game message based on whether the word was revealed
if (wordNotRevealed) {
System.out.println("You've run out of attempts. The hidden word was: " + secretWord);
} else {
System.out.println("Success!!! You've revealed the word: " + new String(gameBoard));
}
Current word: FRIEN_
Success!!!
Guess a letter: D
Good job! You found a match!
Attempts remaining: 9
Success!!! You've revealed the word: FRIEND
www.luv2code.com © luv2code LLC
Word Quest Game - Enhancements
© luv2code LLC
Enhancements
• Refactor variable name
• Change placeholder character
• Read words from a le
fi
www.luv2code.com © luv2code LLC
Refactor variable name // Flag to check if the word has been fully revealed
boolean wordNotRevealed = true;
• Currently we have: wordNotRevealed
• In general, not a good idea to include negative (Not) in the variable
• Can get confusing when you apply: !wordNotRevealed … double negative
• We’ll rename it: hasMissingLetters
• Clearly implies word is incomplete because it has missing letters
• Logical t for boolean for applying not: !hasMissingLetters
fi
• Eliminates double negative
www.luv2code.com © luv2code LLC
Change placeholder character
• Currently the underscores run together
Current word: ______
• Hard to see how many actual letter spaces
• Replace the _ with a - Current word: --------
www.luv2code.com © luv2code LLC
Read words from a file
• Instead of hard-coded array String[] words = {"Java", "Airplane", "Friend"};
• Read the words from a le File: sample-words.txt
fi
Ability
Abstract
Academic
Accent
Achievement
Acquire
Adapt
Advance
Adventure
Agenda
Agility
Agree
Airline
Airspace
...
www.luv2code.com © luv2code LLC
Reading from a File
• Leverage support classes from Java IO libraries
File is relative to your
• Files and Path IntelliJ project
String fileName = "data/sample-words.txt";
// read in all lines from the file
List<String> linesList = Files.readAllLines(Path.of(fileName));
// convert the List to an Array
Collection String[] words = linesList.toArray(new String[0]);
To perform conversion,
We’ll learn more about
List collections need to give 0 length array of target type
later in the course
www.luv2code.com © luv2code LLC
More on File Names
• In general, Java uses forward slashes
• Even works on MS Windows File is relative to your
IntelliJ project
String fileName = "data/sample-words.txt";
String fileName = "c:/Users/luv2code/demo/data/sample-words.txt"; Absolute paths
String fileName = "j:/training/stuff/sample-words.txt";
String fileName = "/home/luv2code/demo/sample-words.txt";
www.luv2code.com © luv2code LLC
More on File Names
• For MS Windows, you can also use backslashes
• But requires special syntax … need to “escape” the backslash
• Because the backslash is a special escape character in Java strings: \n, \t etc …
String fileName = "data\\sample-words.txt";
String fileName = "c:\\Users\\luv2code\\demo\\data\\sample-words.txt";
String fileName = "j:\\training\\stuff\\sample-words.txt";
www.luv2code.com © luv2code LLC
Refactored method Could possibly throw an error/exception:
file not found, permissions etc
private static String getRandomWord(String fileName) throws IOException {
// String[] words = {"Java", "Airplane", "Friend"};
// read in all lines from the file
List<String> linesList = Files.readAllLines(Path.of(fileName));
// convert the List to an Array
String[] words = linesList.toArray(new String[0]);
Random random = new Random();
int index = random.nextInt(words.length);
String theWord = words[index];
We’ll learn more about
Exceptions later in the course
return theWord.toUpperCase();
}
www.luv2code.com © luv2code LLC