1

I have a problem where i want to see if the input user has enterd partially matches, or as long as majority matches with the answer, if it does then it should print out "Almost correct". For example lets say the answer is Football, but user instead puts in Footbol. It should then print out Almost correct.

here is what i tried. But the problem is that it just checks if the whole word is containd in ENG otherwise if even one Char is missing it doesnt work.

     if (Answer.equalsIgnoreCase(ENG)){
        r = "Correct";
    }
    else if (Answer.toLowerCase().contains(ENG.toLowerCase().)){
        r = "Almost correct";
    }
    else {
        r = "Wrong";
    }
    System.out.println(r)
TheGoat27
  • 13
  • 3
  • 1
    Looks like you need some fuzzy matching – Alberto S. Dec 22 '21 at 23:00
  • Split `ENG` into words and count how many are contained, perhaps? – tgdavies Dec 22 '21 at 23:01
  • 1
    Hi & Welcome! Please first *define* "matches more than 60% to the answer" ... how many percent matches "eng" with "gne" (e.g) ? :) (100? 0? 50??:) – xerx593 Dec 22 '21 at 23:17
  • 1
    Sorry i wrote a little bit wrong, ENG contains just one word. I meant to say if the userinput is missing one CHAR then it doesnt recognize it. Like the example above, writing Footbol prints out "Wrong" when it should say Almost Correct. But if the user inputs Footballs then it says Almost correct, as it finds the word Football and the S is just additional. If you understand what i mean. And it doesnt have to be 60% just as long as the majority of CHAR matches with The word in ENG. – TheGoat27 Dec 22 '21 at 23:17
  • 2
    Would soundex answer your needs? https://stackoverflow.com/questions/43275987/implementing-soundex-in-java – passer-by Dec 22 '21 at 23:17

1 Answers1

1

This code is certainly not perfect, but it basically compares the Strings and saves how many characters matched the corresponding character in the other String. This of course leads to it not really working that well with different sized Strings, as it will treat everything after the missing letter as false (unless it matches the character by chance). But maybe it helps regardless:

String match = "example";
String input = "exnaplr";
int smaller;
if (match.length() < input.length())
    smaller = match.length(); else smaller = input.length();
int correct = 0;
for (int i = 0; i < smaller; i++) {
    if (match.charAt(i) == input.charAt(i)) correct++;
}
int percentage = (int) ((double) correct / match.length() * 100);

System.out.println("Input was " + percentage + "% correct!");
mousekip
  • 117
  • 10