Пытаюсь сравнить буквы от пользователя и фразу. Я хочу, чтобы он шел по каждой букве. У меня есть "if ((userGuessLength / phraseLength * 100.0) > 75.0)
" в качестве заполнителя, чтобы просто сравнить длины строк, но он мне нужен для сравнения каждой буквы в строке.
как бы мне это изменить?
Пример:
Где-то над радугой. - актуальная фраза
Где-то над xxxxxxx. - предположение пользователя
19 символов правильные (включая пробелы) 26 символов - фактическая длина фразы
(19/26) * 100 = 73
процента (упустили)
Это вся моя программа:
package classprojects;
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.util.Random;
public class WordGame {
public static void main(String[] args) {
String userInput = " "; // userInput
Random rand = new Random();
Scanner word = new Scanner(System.in);
int n = rand.nextInt(14);
String underscores = ""; // holder for changing characters to *
String update = ""; // this is updated from underscores and displayed
String[] phrases = new String[15];
// Phrases used in Array
phrases[0] = "dog eat dog world";
phrases[1] = "a penny for your thoughts";
phrases[2] = "at the drop of a hat";
phrases[3] = "ball is in your court ";
phrases[4] = "back to the drawing board ";
phrases[5] = "barking up the wrong tree";
phrases[6] = "beat around the bush";
phrases[7] = "best of both worlds";
phrases[8] = "bite off more than you can chew";
phrases[9] = "blessing in disguise";
phrases[10] = "cant judge a book by its cover";
phrases[11] = "costs an arm and a leg";
phrases[12] = "curiosity killed the cat";
phrases[13] = "dont put all your eggs in one basket";
phrases[14] = "elvis has left the building";
double phraseLength = phrases[n].length();
//loop for changing characters in array to * and replacing correct letter from the userInput
while (true) {
for (int l = 0; l < 5; l++) {
for (int i = 0; i < phraseLength; i++) {
char theChar = phrases[n].charAt(i);
if (theChar == ' ') {
underscores += ' ';
update = underscores;
} else
for (int j = 0; j < userInput.length(); j++) {
char compare = userInput.charAt(j);
if (theChar == compare) {
underscores += compare;
update = underscores;
break;
} else if (j == userInput.length() - 1) {
underscores += "*";
update = underscores;
}
}
}
//prints the updated phrase with * and letters that were correctly guessed, and prompts user to continue to enter letters
System.out.println(phrases[n]);
System.out.println("Start by Entering a Letter to Guess the Phrase: " + update);
System.out.println("Enter A Letter: ");
//takes the keyboard input and makes it all lower case and
//restarts underscores so phrase does not stack
String letterGuess = word.next();
String letterGuessL = letterGuess.toLowerCase();
userInput += letterGuessL;
underscores = "";
}
//Display after 5 turns
int userReply = JOptionPane.showConfirmDialog(null, "Do you know the phrase? If not continue guessing.",
"Guess", JOptionPane.YES_NO_OPTION);
//if yes then it takes the length of your guess and divides it by the phrase and check if its over 75%
if (userReply == 0) {
String userGuess = JOptionPane.showInputDialog("What is your guess?");
double userGuessLength = userGuess.length();
if ((userGuessLength / phraseLength * 100.0) > 75.0) {
JOptionPane.showMessageDialog(null, "Correct, you WIN! That was the correct phrase: " + phrases[n]);
break;
} else {
int userReply2 = JOptionPane.showConfirmDialog(null,
"Sorry that is wrong, Do you want to continue going?", "Wrong", JOptionPane.YES_NO_OPTION);
if (userReply2 == 0) {
} else {
JOptionPane.showMessageDialog(null, "The game is OVER. The correct phrase was: " + phrases[n]);
break;
}
}
}
}
}
}
Почему бы не взять правильную строку и не поместить ее в char[]
, а затем сделать то же самое с вводом пользователя. Затем вы можете провести прямое сравнение с использованием индексов и увеличить счетчик для каждой правильной буквы.
Я попытался использовать аналогичный цикл for из моего кода, где он заменяет каждую букву на *, а не заменяет просто count
у вас есть пример или голый код того, что я могу видеть аскалонский?
На самом деле char [] вам не нужен. А как насчет цикла for-loop if (correctString.charAt(i) == inputString.charAt(i)) { correctCounter++;}
или чего-то в этом роде - конечно, имея в виду длину строки
убедиться, что для сравнения используется более короткая из двух строк, чтобы не возникла ошибка?
Есть много способов сделать это. Вот один из способов использования потока вместо явного цикла:
String answer = "Somewhere over the rainbow";
String guess = "Somewhere over the xxxxxxx";
long correct = IntStream.range(0, Math.min(answer.length(), guess.length()))
.filter(i -> answer.charAt(i) == guess.charAt(i)).count();
int total = Math.max(answer.length(), guess.length());
System.out.format("(%d/%d) = %d%%%n", correct, total, correct*100/total);
Выход:
(19/26) = 73%
private static double getCorrectness(String actualPhrase, String userGuess) {
char [] actual = actualPhrase.toCharArray();
char [] guess = userGuess.toCharArray();
int length = Math.min(actual.length, guess.length);
for(int counter = 0;counter<length ;counter++) {
//case sensitive
if (actual[counter]!=guess[counter]) {
return counter*100.0/actual.length;
}
}
return length*100.0/actual.length;
}
что делать, если предположение короче фактического?
Вам также не нужно использовать char[]
, вы можете просто использовать actual.charAt(counter)
отредактирован для более короткого предположения. Да, вместо него можно использовать charAt
.
Покажите нам, что вы пытались решить эту проблему. Это работает? Если нет, то что не работает?