Цикл, сравнивающий отдельные буквы в строке

Пытаюсь сравнить буквы от пользователя и фразу. Я хочу, чтобы он шел по каждой букве. У меня есть "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;
                }

            }
        }
    }
}
}

Покажите нам, что вы пытались решить эту проблему. Это работает? Если нет, то что не работает?

user9455968 01.05.2018 19:25

Почему бы не взять правильную строку и не поместить ее в char[], а затем сделать то же самое с вводом пользователя. Затем вы можете провести прямое сравнение с использованием индексов и увеличить счетчик для каждой правильной буквы.

Ascalonian 01.05.2018 19:30

Я попытался использовать аналогичный цикл for из моего кода, где он заменяет каждую букву на *, а не заменяет просто count

Hunter Gibson 01.05.2018 19:31

у вас есть пример или голый код того, что я могу видеть аскалонский?

Hunter Gibson 01.05.2018 19:33

На самом деле char [] вам не нужен. А как насчет цикла for-loop if (correctString.charAt(i) == inputString.charAt(i)) { correctCounter++;} или чего-то в этом роде - конечно, имея в виду длину строки

Ascalonian 01.05.2018 19:33

убедиться, что для сравнения используется более короткая из двух строк, чтобы не возникла ошибка?

Hunter Gibson 01.05.2018 19:38
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
1
6
106
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Есть много способов сделать это. Вот один из способов использования потока вместо явного цикла:

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;
}

что делать, если предположение короче фактического?

Patrick Parker 01.05.2018 20:54

Вам также не нужно использовать char[], вы можете просто использовать actual.charAt(counter)

Ascalonian 01.05.2018 21:21

отредактирован для более короткого предположения. Да, вместо него можно использовать charAt.

dev. K 02.05.2018 10:16

Другие вопросы по теме