Here goes. I am having trouble with an assignment in Java. We are asked to create a program where the user needs to guess letters from a missing phrase. I created the phrase and replaced each character with a ?, but now the user needs to guess. How do I construct the for loop to reveal each character if the user is correct. This is what I have so far on eclipse.
public static void main(String[]args)
{
Scanner stdIn = new Scanner(System.in);
String cPhrase = "be understaning";
char g;
boolean found;
String guessed;
System.out.println("\tCommon Phrase");
System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _");
System.out.println(cPhrase.replaceAll("[a-z]", "?"));
System.out.println(" ");
System.out.print(" Enter a lowercase letter guess: ");
g = stdIn.nextLine(); // I am trumped right here not sure what to do?
// Can't convert char to str
for (int i = 0; i < cPhrase.length(); ++i)
{
if( cPhrase.charAt(i) == g)
{
found = true;
}
if (found)
{
guessed += g;
You're almost there.
Use a while instead of a for loop tied to a boolean condition. The boolean would be set to false if and only if all characters in word guessed.
You could simply get the first char of the input-line (assuming one should just guess one char at a time)
g = stdIn.nextLine().charAt(0);
To loop until the user has guessed the whole phrase you need to surround the code with a while
.
while(not complete)
{
get input
process input
show progress
}
Here is a quick soluition. But please dont just copy-paste, you still need to understand it (therefor i put inline-comments in).
public static void main(String[] args)
{
Scanner stdIn = new Scanner(System.in);
String phrase = "be understanding";
boolean[] guessed = new boolean[phrase.length()];
// walk thru the phrase and set all non-chars to be guessed
for (int i = 0; i < phrase.length(); i++)
if (!phrase.substring(i, i + 1).matches("[a-z]"))
guessed[i] = true;
// loop until we break out
while (true)
{
System.out.print("Please guess a char: ");
char in = stdIn.nextLine().charAt(0);
boolean allGuessed = true;
System.out.print("Phrase: ");
// walk over each char in the phrase
for (int i = 0; i < phrase.length(); i++)
{
char c = phrase.charAt(i);
// and check if he matches the input
if (in == c)
guessed[i] = true;
// if we have an not already guessed char, dont end it
if (!guessed[i])
allGuessed = false;
// print out the char if it is guessed (note the ternary if operator)
System.out.print(guessed[i] ? c : "?");
}
System.out.println("\n------------------");
// if all chars are guessed break out of the loop
if (allGuessed)
break;
}
System.out.println("Congrats, you solved the puzzle!");
stdIn.close();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.