3 回答
TA贡献1841条经验 获得超3个赞
请尝试下面提到的解决方案。
String[] validOperators = {"+", "-", "/", "*", "=", "q", "Q"};
String userInput;
Scanner scanner = new Scanner(System.in);
Arrays.sort(validOperators);
do{
System.out.print("Please enter a valid operation ( +, -, /, *, = , q or Q ) to quit: ");
userInput = scanner.nextLine();
}while(Arrays.binarySearch(validOperators, userInput) <= -1);
TA贡献1797条经验 获得超6个赞
我宁愿使用数组和流,从Java 8开始就可用。例如:
Arrays.stream(validOperators).anyMatch(userInput::equals)
如果你需要一个更好的性能解决方案来满足一小部分元素,那么内存和进程都有效,并且不使用语法糖或Java 8流(而由于Vinod Singh Bist,循环更清晰,改进):
public static void main(String[] args) {
char[] validOperators = {'+', '-', '/', '*', '=', 'q', 'Q'}; // String is more expensive
char userInput;
Scanner scanner = new Scanner(System.in);
do{
System.out.print("Please enter a valid operation ( +, -, /, *, = , q or Q ) to quit: ");
userInput = scanner.next().charAt(0);
}while(!contains(validOperators, userInput)) ;
}
private static boolean contains(char[] elements, char c) {
// for loop is usually faster for small lists than any built-in iterator for primitives like char
for (int i = elements.length - 1; i >= 0; i--) {
if (elements[i] == c) {
return true;
}
}
return false;
}
TA贡献1851条经验 获得超5个赞
Arrays.binarySearch(validOperators, userInput)
需要排序数组。
如果数组不是 ,则结果为 。你应该你sorted
undefined
Arrays.sort(validOperators);
添加回答
举报