В массиве
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
Не стесняйтесь комментировать в случае каких-либо сомнений / проблем.