在带有验证的while循环内输入字符

时间:2018-08-25 02:56:12

标签: java

System.out.print("Enter the operator (+ - X /): ");
operator = input.next();
char c=operator.charAt(0);
while (c != '+' && c != '-' && c != '*' && c != '/'){
    System.out.println("Operator doesn't match. Try again.");
    System.out.print("Enter the operator (+ - X /): ");
    input.next().charAt(0);
}

在这里,我想从键盘输入一个字符值,该值仅是while循环内的(+-* /)符号。如果符号不匹配,则while循环将运行。

此处while循环正在工作,但未检查字符。因此,虽然while循环持续与-

System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X /): ");

1 个答案:

答案 0 :(得分:1)

在while循环的最后一行中,您正在检索用户输入,但未将其存储在任何地方。您应该这样做:

c = input.next().charAt(0);

如果您想做点花哨的事情,也可以尝试使用do-while loop,如下所示:

char c;
do {
    System.out.println("Enter a operator (+ - * /):");
    c = input.next().charAt(0);
} while(c != '+' && c != '-' && c != '*' && c != '/');