Section 05 Arrays
Section 05 Arrays
© luv2code LLC
Arrays
• An array is a data structure that holds multiple elements of the same typ
• Array of Strings
• Array of ints
100 76 89
• Buffering dat
a
• …
fi
e
fi
0 1 2 3
Re
Gree
// initialize the arra
Blu
y
System.out.println(colors[0]);
System.out.println(colors[2])
;
System.out.println(colors[3])
Index to an element in the array
;
Length attribute
System.out.println(colors[0]) Gree
System.out.println(colors[1]) Blu
System.out.println(colors[2])
Yello
System.out.println(colors[3])
Remember,
arrays are 0-based // loop through the array - version
System.out.println(colors[i])
Blu
Yellow
System.out.println(temp)
Re
Blu
© luv2code LLC
Arrays - Initialization
• Previously, we speci ed the contents during initialization
fi
// initialize the arra
• What if we wanted to specify the size of the array … but add data later??
… … …
0 1 2
// initialize the arra
0 1 2
grades[0] = 100.0 ;
0 1 2
grades[1] = 76.7
;
grades[0] = 100.0
grades[1] = 76.7;
grades[2] = 89.0
;
System.out.println(temp) 76.
89.0
}
• Initialize the array based on the number of grade Enter grade number 1: 100.0
76.
94.
88.4
76.
userInputGrades[i] = scanner.nextDouble()
94.
88.4
}
System.out.println()
;
System.out.println(temp)
;
scanner.close();
© luv2code LLC
Computing Grade Average
• We currently have an array of grades
Return type Input parameter Must use exact same type: double[ ]
sum += temp
;
return average;
}
..
.
userInputGrades[i] = scanner.nextDouble()
private static double computeGradeAverage(double[] userInputGrades)
scanner.close();
// compute the grade average, based on length of the arra
return average
© luv2code LLC
Refactor
• Let’s refactor our app to return an array from a metho
// initialize the array based on the number of grade Enter grade number 2: 76.7
userInputGrades[i] = scanner.nextDouble()
scanner.close()
;
double gradeAverage = computeGradeAverage(userInputGrades) // prompt the user for how many grade
System.out.println("Grade average: " + gradeAverage) System.out.print("How many grades will you enter? ")
}
System.out.println()
userInputGrades[i] = scanner.nextDouble()
scanner.close()
return userInputGrades
© 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
0 1 2
fi
h
Arrays.fill(myDataArray, theNum)
;
System.out.println()
;
System.out.println(temp)
;
scanner.close();
© luv2code LLC
Sorting an Array
• We can use the method: Arrays.sort(theArray)
0 1 2
// initialize the arra 61 4 25
Arrays.sort(myData)
;
0 1 2
4 25 61
Enter number 1: 6
Enter number 2:
• Prompt user for the array content
Enter number 3: 2
• 2
AFTER sorting
• Sort the array
System.out.print("What size array do you want? ") What size array do you want? 3
myDataArray[i] = scanner.nextInt()
2
}
System.out.println()
;
AFTER sorting
System.out.println("BEFORE sorting:")
displayData(myDataArray) 2
61
System.out.println()
;
Arrays.sort(myDataArray)
;
System.out.println(temp)
scanner.close(); }
© luv2code LLC
Searching an Array
• We can use the method: Arrays.binarySearch(theArray, theSearchKey)
• 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
int searchKey = 4
Enter number 1: 6
• Initialize the array based on the siz What number do you want to search for? 4
Found: tru
Prompt user for the search key
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?
System.out.println()
Found: tru
;
Arrays.sort(myDataArray)
;
if (found)
{
else
{
scanner.close();
© luv2code LLC
2D Arrays
• Represent a grid of data
1 2 3 4
2 4 6 8
3 6 9 12
4 8 12 16
5 10 15 20
• Matrix calculations
• Seating charts
• Image processing
• Route navigation
• others …
0 1 2
0 0 0 0
1 0 0 0
0 1 2 3
0 90 85 100 93
1 60 70 80 87
System.out.println(tableDemo[0][2]);
System.out.println(tableDemo[1][3]);
100
87
Row Col
System.out.println();
© luv2code LLC
Number Guessing Game
• Let’s have some fun and create a number guessing game!
Success!!!
Failure
• 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.
• If the guess is correct, print a success message and end the game
• If all attempts are used without a correct guess, reveal the secret number
© luv2code LLC
Word Quest Game
• Let’s develop a word quest game!
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
• If all attempts are used without a revealing all of the letters, reveal the secret word
// 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!");
Guess a letter: e
Good job! You found a match!
Attempts remaining: 9
// 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
© luv2code LLC
Enhancements
• Refactor variable name
fi
www.luv2code.com © luv2code LLC
Refactor variable name // Flag to check if the word has been fully revealed
boolean wordNotRevealed = true;
fi
Ability
Abstract
Academic
Accent
Achievement
Acquire
Adapt
Advance
Adventure
Agenda
Agility
Agree
Airline
Airspace
...
To perform conversion,
We’ll learn more about
List collections need to give 0 length array of target type
later in the course
• Because the backslash is a special escape character in Java strings: \n, \t etc …