Unit 2 Objects
public class WordMatch
{
/** The secret string. */
private String secret;
/** Constructs a WordMatch object with the given secret string of lowercase letters. */
public WordMatch(String word)
{
/* implementation not shown */
this.secret = word;
}
/** Returns a score for guess, as described in part (a).
* Precondition: 0 < guess.length() <= secret.length()
*/
// START OF SOLUTION A
public int scoreGuess(String guess) {
// Tracks number of times the substring appears
int occurrences = 0;
// secret.length() - guess.length() to avoid index overflow with substring later on
for (int i = 0; i <= secret.length() - guess.length(); i++) {
// Checks if the substring is equal to the guess
if (secret.substring(i, i + guess.length()).contains(guess)) {
occurrences++;
// Moves forward by guess.length() - 1 to move forward in the string (and avoid repeats)
// -1 is included because i++
i += guess.length() - 1;
}
}
return occurrences * guess.length() * guess.length();
}
// END OF SOLUTION A
// START OF SOLUTION B
public String findBetterGuess(String guess1, String guess2)
{ /* to be implemented in part (b) */
if (scoreGuess(guess1) > scoreGuess(guess2)) {
return guess1;
} else if (scoreGuess(guess2) > scoreGuess(guess1)) {
return guess2;
} else if (guess1.compareTo(guess2) > 0) {
return guess1;
} else {
return guess2;
}
}
// END OF SOLUTION B
public static void main(String[] args) {
WordMatch testA = new WordMatch("mississippi");
System.out.println(testA.scoreGuess("issippi"));
System.out.println(testA.scoreGuess("mississippi"));
WordMatch testB = new WordMatch("concatenation");
System.out.println(testB.findBetterGuess("ten" , "nation"));
System.out.println(testB.findBetterGuess("con", "cat"));
}
}
WordMatch.main(null);
Extra Notes
Concatenation
Concatenation is the process of combining 2 or more strings together to form 1 string. It's pretty simple to do with just the "+" operator between two strings (or alternatively the concat() method). Using mixed datatypes together is also pretty easy, as Java will automatically cast different datatypes into Strings when needed, making the entire process much easier.
int numOfCats = 34;
String sentencep1 = "I have ";
System.out.println("I have 34 cats!");
System.out.println("I have " + numOfCats + " cats!");
Math Class
The Math class is one class that is useful for many programmers, especially considering its numerous mathematical operations that are necessary in a math-heavy field like computer science. One such method is Math.random(), which can allow programmers to simulate randomness (to a certain extent) by generating a random double from 0 to just below 1, which can be edited to encompass nearly any range of numbers.
// Randomnly prints out a number from 1 to 10
System.out.println((int)(Math.random() * 10 + 1));