Как проверить строку в массиве для метода в java - PullRequest
2 голосов
/ 06 апреля 2020

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

String[] options1 = { "a", "b", "c" };  
choice = getValidString(sIn, "Please enter 'a', 'b' or 'c': ",
             "Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.",
             options1); // call method
System.out.printf("The letter your entered was: %s\n\n", choice);

public static String getValidString(Scanner sIn, String question,
                                    String warning, String[] choices)
    String input = "";
    boolean valid= false;
    do {
        System.out.println(question);
        input = sIn.nextLine();
        try {
            Arrays.asList(choices).contains(input); // this is where the problem resides.
            valid = true;
        } catch(Exception e) {
        System.out.println(warning); } 
    } while (!valid);
    return input ;
}

Требуемый вывод :

Please enter 'a', 'b' or 'c': hypotenuse.
Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.
Please enter 'a', 'b' or 'c': b
The letter your entered was: b

1 Ответ

0 голосов
/ 06 апреля 2020
В массиве

A Java нет методов, подобных contains. Преобразуйте массив в List, используя Arrays.asList, и затем вы можете применить contains к результирующему List.

import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sIn = new Scanner(System.in);
        String[] options1 = { "a", "b", "c" };
        String choice = getValidString(sIn, "Please enter 'a', 'b' or 'c': ",
                "Invalid response. Only the letters 'a', 'b' or 'c' are acceptable.", options1); // call mehtod
        System.out.printf("The letter your entered was: %s\n\n", choice);
    }

    public static String getValidString(Scanner sIn, String question, String warning, String[] choices) {

        String input = "";
        boolean valid = false;
        List<String> choiceList = Arrays.asList(choices);
        do {
            System.out.println(question);
            input = sIn.nextLine();
            try {
                valid = choiceList.contains(input);
                valid = true;
            } catch (Exception e) {
                System.out.println(warning);
            }
        } while (!valid);
        return input;
    }
}

Пример выполнения:

Please enter 'a', 'b' or 'c': 
b
The letter your entered was: b

Не стесняйтесь комментировать в случае каких-либо сомнений / проблем.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...