Reputation: 357
Using the code below, the loop does not end when I use +, - and 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();
}
Why this happens and how can I implemented with the right way?
Upvotes: 0
Views: 74
Reputation: 642
I'd rather use Arrays and Streams, available since Java 8. For example :
Arrays.stream(validOperators).anyMatch(userInput::equals)
If you need a better performance solution for a small list of elements, both memory and process efficient and that doesn't use syntactic sugar or Java 8 streams (while loop is clearer and improved thanks to 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;
}
Upvotes: 1
Reputation: 327
Try below mentioned solution.
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);
Upvotes: 1
Reputation: 1371
Arrays.binarySearch(validOperators, userInput)
require sorted array.
If array is not sorted
, the results are undefined
. You should you Arrays.sort(validOperators);
Upvotes: 1