Basic Java beginner here.
My assignment is to first print the prompt "Enter the secret word: ", then write a method in which the user would enter a "Secret Word", and convert that word to uppercase. Then I need to check if the "Secret Word" contains only letters. If not they will be re-prompted until they meet the specific criteria of only letters. Between receiving any incorrect responses and printing the prompt again, it should print "A secret word may only contain letters."
The last criteria of this assignment is using my already correct and tested Method wordContainsNonLetter in order to test if my "Secret Word" contains only letters.
I then must return the "Secret Word" at the very end.
I've tried a couple things but nothing really seems to do what I want it to do.
This is my main.
public class GuessingGame {
public static void main(String [] args) {
Scanner console = new Scanner(System.in);
//System.out.print(wordContainsNonLetter("15th"));
System.out.print(getSecretWord(console));
}
This is the wordContainsNonLetter method.
public static boolean wordContainsNonLetter(String word) {
boolean valid = false;
int pos = 0;
while(!valid && pos < word.length()) {
char letter = word.charAt(pos);
if (!Character.isAlphabetic(letter)){
valid = true;
}
pos ++;
}
return valid;
}
This is the incorrect getSecretWord method
public static String getSecretWord(Scanner console) {
String secretWord = "";
boolean valid = false;
System.out.print("Enter the secret word: ");
String word = console.nextLine();
String upperWord = word.toUpperCase();
while (valid);
{
if(wordContainsNonLetter(upperWord) == false) {
upperWord = secretWord;
}
else {
System.out.println("A secret word may only contain letters.");
System.out.print("Enter the secret word: ");
upperWord = console.nextLine();
}
return secretWord;
}
}
}
My expected result should look something like this (The first 3 attempts are proving that the method correctly works)
Enter the secret word: Caputo 130
A secret word may only contain letters.
Enter the secret word: Caputo One-Thirty
A secret word may only contain letters.
Enter the secret word: Caputo One Thirty
A secret word may only contain letters.
Enter the secret word: Labroo
It then would return "LABROO"
Aucun commentaire:
Enregistrer un commentaire