|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
SlickEdit: Code in over 40 languages across 7 platforms. SlickEdit’s unmatched power, speed, and flexibility allows even the most accomplished developers to write better code faster. Download a free trial today! |
|
#1
|
|||
|
|||
|
Homework - Java 'Hangman' help
So, I am working on a hangman assignment, the program is supposed to run like this,
//Secret word _ _ _ _ _ //Wrong guesses: //Guess a letter:e //Secret word _ e _ _ _ //Wrong guesses: //Guess a letter:r //Secret word _ e _ _ _ //Wrong guesses: r //Guess a letter:l //Secret word _ e l l _ //Wrong guesses: //Guess a letter:e --------------------------------------------------------- So, the user enters a letter, and the program is supposed to check weather or not the letter is in the string (the secret word is chosen at random I highlighted the code) 'Secret word'. If the letter is in the string then it replaces the underscore, if it is incorrect the letter gets put in the 'Wrong guesses' list. Here is what I have so far, this program just uses a for loop to allow the user to keep on guessing. I cannot figure out how to replace the underscores or check weather or not the letter is in the string in the first place... Any help would be nice... Code:
java.util.*;
public class Testing{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
Scanner console = new Scanner(System.in);
String answer = HangmanUtils.getWord();
CountLetters(answer);
}
public static String GetWord (){
String answer = HangmanUtils.getWord();
return answer;
}
public static String CountLetters(String answer) {
Scanner console = new Scanner(System.in);
int i = 0;
while((i >= 0) && (i <= 4)){
i++;
System.out.println();
System.out.print("Secret word: "+answer);
int count = 0;
for (int j = 0; j< answer.length();j++) {
char ch = answer.charAt(j);
if (Character.isLetter(ch)){
count++;
System.out.print("_ ");
}
}
System.out.println();
System.out.print("Wrong guesses: ");
System.out.println();
System.out.print("Guess a letter: ");
char guess = console.next().charAt(0);
for (int k = 0; k <answer.length(); k++) {
if (answer.charAt(k) == guess) {
System.out.print(guess);
}else{
System.out.print(guess);
}
}
}
return answer;
}
}
|
|
#2
|
|||
|
|||
|
Quote:
I think you should start by looking at the methods in the String class. Try to use String.contains(..) and String.replace(...) |
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Java Help > Homework - Java 'Hangman' help |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|