使用下面的代码,当我使用+,-和Q时循环不会结束。
String[] validOperators = {"+", "-", "/", "*", "=", "q", "Q"};
String userInput;
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter an operation (+, -, /, *, = or Q to quit): ");
userInput = scanner.nextLine();
while(Arrays.binarySearch(validOperators, userInput) <= -1) {
System.out.print("Invalid input (+, -, /, *, = or Q to quit): ");
userInput = scanner.nextLine();
}
为什么会发生这种情况,如何以正确的方式实施?
答案 0 :(得分:1)
我宁愿使用Java 8以来可用的Arrays和Streams。例如:
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;
}
答案 1 :(得分:1)
Arrays.binarySearch(validOperators, userInput)
需要排序的数组。
如果数组不是sorted
,则结果为undefined
。您应该Arrays.sort(validOperators);
答案 2 :(得分:1)
请尝试以下提到的解决方案。
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);