猿问

扫描仪和用户输入

使用下面的代码,当我使用+,-和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();

}

为什么会发生这种情况,我如何以正确的方式实施?


慕婉清6462132
浏览 116回答 3
3回答

偶然的你

请尝试下面提到的解决方案。&nbsp; &nbsp; String[] validOperators = {"+", "-", "/", "*", "=", "q", "Q"};&nbsp; &nbsp; String userInput;&nbsp;&nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; Arrays.sort(validOperators);&nbsp; &nbsp; do{&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Please enter a valid operation ( +, -, /, *, = , q or Q ) to quit: ");&nbsp; &nbsp; &nbsp; &nbsp; userInput = scanner.nextLine();&nbsp; &nbsp; }while(Arrays.binarySearch(validOperators, userInput) <= -1);

互换的青春

我宁愿使用数组和流,从Java 8开始就可用。例如:Arrays.stream(validOperators).anyMatch(userInput::equals)如果你需要一个更好的性能解决方案来满足一小部分元素,那么内存和进程都有效,并且不使用语法糖或Java 8流(而由于Vinod Singh Bist,循环更清晰,改进):public static void main(String[] args) {&nbsp; &nbsp; char[] validOperators = {'+', '-', '/', '*', '=', 'q', 'Q'}; // String is more expensive&nbsp; &nbsp; char userInput;&nbsp; &nbsp; Scanner scanner = new Scanner(System.in);&nbsp; &nbsp; do{&nbsp; &nbsp; &nbsp; &nbsp; System.out.print("Please enter a valid operation ( +, -, /, *, = , q or Q ) to quit: ");&nbsp; &nbsp; &nbsp; &nbsp; userInput = scanner.next().charAt(0);&nbsp; &nbsp; }while(!contains(validOperators, userInput)) ;}private static boolean contains(char[] elements, char c) {&nbsp; &nbsp; // for loop is usually faster for small lists than any built-in iterator for primitives like char&nbsp; &nbsp; for (int i = elements.length - 1; i >= 0; i--) {&nbsp; &nbsp; &nbsp; &nbsp; if (elements[i] == c) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false;}

江户川乱折腾

Arrays.binarySearch(validOperators, userInput)需要排序数组。如果数组不是 ,则结果为 。你应该你sortedundefinedArrays.sort(validOperators);
随时随地看视频慕课网APP

相关分类

Java
我要回答