Сравните ввод с List <String>, сообщите пользователю, правильный ли ввод, почти правильный или неправильный - PullRequest
0 голосов
/ 03 августа 2020

Я новичок в java, поэтому извиняюсь, если код заставляет ваши глаза кровоточить. Я должен сделать простой "тест глоссария" на шведском sh на английский sh.

Я использовал hashmap для хранения словаря. У меня возникают проблемы, когда сравнивать вводимые пользователем данные с правильными переводами.

Я создал for l oop, который проходит через массив переводов. В этом l oop я хотел бы проверить вводимые пользователем строки со строками в этом массиве и сохранить правильные ответы (количество правильных ответов) и I (сколько вопросов было задано).

Я могу ' t получить правильные значения, и я обновлю правильно.

Также мне не удается найти хороший способ сравнить ввод со строкой для проверки правильности.

Мой код:

import java.util.*;

    public class MyClass {

        public static void main(String[] args) {
            Mainmenu();
            getDictionary();
        }

        private static void Mainmenu() {
            System.out.println("** GLOSÖVNING-ENGELSKA **");
            System.out.println("Write the English word for the given Swedish. Quit by pressing Q ");
         //   System.out.println("the dictionary is : " + getDictionary()); // to see that the dictionary is correct
        }

        private static Map<String, List<String>> getDictionary() {

            Map<String, List<String>> map = new HashMap<>();
            String[][] dictionary = {
                    // Swedish, Translation1, Translation2, ...
                    {"bil", "car"},
                    {"snäll", "kind"},
                    {"kör", "drives", "choir"},
                    {"hej", "hello"},
                    {"äpple", "apple"},
                    {"kort", "short"}

            };
            for (String[] entry : dictionary) {
                String sweWord = entry[0]; // E.g. "kör"
                List<String> translations = new ArrayList<>();
                for (int i = 1; i < entry.length; i++) {    // skips the first (swedish) word
                    translations.add(entry[i]); // e.g. "drives"

                }
                map.put(sweWord, translations);
                Querywords(map, sweWord, translations);
            }

            return map;
        }
// The swedish words asked
        private static List<String> Querywords(Map<String, List<String>> map, String sweWord, List<String> translations) {
            System.out.println(sweWord + ":");
            List<String> translation = Translation(sweWord, translations, map);
            return translation;
        }
// The correct answer/answers.
        private static List<String> Translation(String sweWord, List<String> translation, Map map) {
            Scanner scanner = new Scanner(System.in);
            String inputString = scanner.nextLine().trim();
            int correctans=0;


            // add: to quit when Q is pressed
            for (int i=0; i < translation.size(); i++)  {
                boolean correct = translation.get(i).equalsIgnoreCase(inputString);
                if (correct == true) {
                    correctans++;
                    System.out.println(translation.get(i));
                 //   System.out.println(translation+"translation"+i); for me to se that the code knows the right answer(s)..
                    System.out.println("Correct! " + correctans + "of " + i + " questions.");
                } else {

                    System.out.println("wrong"); //more code


                }

            }
            return translation;
        }
    }

1 Ответ

0 голосов
/ 03 августа 2020

Чтобы получить количество вопросов, просто используйте размер карты, поскольку вы позволяете пользователю вводить ответы для всех ваших ключей в словарях, а для вашей проблемы с подсчетом, пожалуйста, найдите простой фрагмент кода. вы можете использовать как показано ниже:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class Dict {
    public static void main(String[] args) {
    
        int correct=0;
    
        System.out.println("** GLOSÖVNING-ENGELSKA **");
        System.out.println("Write the Swedish word for the given English. Quit by pressing Q ");
        
        Map<String, List<String>> map = new HashMap<String, List<String>>();
        
        List<String> setone = new ArrayList<String>();
        setone.add("bil");
        setone.add("vagn");
        setone.add("godsfinka");
      
        List<String> settwo = new ArrayList<String>();
        settwo.add("slag");
        settwo.add("snall");
        
        List<String> setthree = new ArrayList<String>();
        setthree.add("halla");
        setthree.add("Hoy");
      
        map.put("car", setone);
        map.put("kind", settwo);
        map.put("hello", setthree);
        
        
        for (Map.Entry<String, List<String>> entry : map.entrySet()) {
            String key = entry.getKey();
        
            System.out.println(key +":");
            Scanner scanner = new Scanner(System.in);
            String inputString = scanner.nextLine().trim();
            if (entry.getValue().contains(inputString)){
            correct++;
            System.out.println("Correct!" + correct + "of" + map.size());
            } else {
            System.out.println("Wrong!" + correct + "of" + map.size());
           }
       }
    }
 }
...