Answer the question
In order to leave comments, you need to log in
How would this code look like in Java?
Good evening guys!
Please tell the pintonist how to implement this code in Java:
The essence of the game - the player tries to guess the word by entering letters!
word = "moloko" #слово которое нужно угадать
so_far = "x" * len(word) по одному x на букву, которую надо угадать
# пока слово не угадано
while so_far != word:
Просим пользователя ввести букву
guess = input("")
если буква есть в слове, которое надо угадать
if guess in word:
new = "" #создаем пустую строку для добавления элементов
for i in range(len(word)):#итерация выполняется 6 раз(длина слова)
if guess==word[i]: #если буква есть угадываемом слове
new = new + guess #добавляем в переменную букву
print(new)
else:#иначе
new = new + so_far[i] #добавляем x
print(new)
# print(so_far[i])
so_far = new
Answer the question
In order to leave comments, you need to log in
import java.util.Scanner;
public class GuessAWord {
private static final String word = "moloko";
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Угадайте слово");
int wordLenght = word.length();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < wordLenght; i++) {
stringBuilder.append("-");
}
String maskWord = stringBuilder.toString();
System.out.println(maskWord);
do {
System.out.print("Введите букву: ");
char c = input.next().charAt(0);
if (word.toLowerCase().indexOf(c) >= 0) {
System.out.println("Есть такая буква в алфавите!");
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == c) {
maskWord = replaceLetter(Character.toString(c), maskWord);
}
}
System.out.println(maskWord);
} else {
System.out.println("Промах. Давай ещё!");
}
} while (maskWord.contains("-"));
}
private static String replaceLetter(String letter, String maskWord) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) == letter.charAt(0)) {
stringBuilder.append(letter);
} else if (maskWord.charAt(i) != '-') {
stringBuilder.append(maskWord.charAt(i));
}
else {
stringBuilder.append("-");
}
}
return stringBuilder.toString();
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question