在这里,在我的代码中,我需要检查一个具有布尔值的字符。为此,我创建了一个布尔方法并检查了字符输入,但是当我在while循环中使用此方法时,出现了一些错误。因此,现在该怎么做才能进行字符验证。我的代码看起来像-
class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your character: ");
String operator = input.next();
char c=operator.charAt(0);
public static boolean isNotChar(char c){
boolean returnValue;
if(c != '+' || c != '-' || c != '*' || c != '/' || c != '^'){
returnValue = true;
}else{
returnValue = false;
}
return returnValue;
}
boolean b1 = isNotChar(c);
while (b1 == true){
System.out.println("Operator doesn't match. Try again.");
System.out.print("Enter the operator (+ - X / ^): ");
c = input.next().charAt(0);
}
System.out.println("Your character is "+c);
}
}
我的错误就像-
E:\java>javac Test.java
Test.java:14: error: illegal start of expression
public static boolean isNotChar(char c){
^
Test.java:26: error: illegal start of type
while (b1 == true){
^
Test.java:26: error: <identifier> expected
while (b1 == true){
^
Test.java:31: error: <identifier> expected
System.out.println("Your character is "+c);
^
Test.java:31: error: illegal start of type
System.out.println("Your character is "+c);
^
Test.java:33: error: class, interface, or enum expected
}
^
6 errors
我应该如何为其创建布尔方法?
代码的解决方案是:-
class Test{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter your character: ");
String operator = input.next();
char c=operator.charAt(0);
boolean b1 = isNotChar(c);
while (b1 == false){
System.out.println("Character doesn't match. Try again.");
System.out.print("Enter the Character from (+ - X / ^): ");
c = input.next().charAt(0);
b1 = isNotChar(c);
}
System.out.println("Your character is "+c);
}
public static boolean isNotChar(char c){
boolean returnValue;
if(c != '+' && c != '-' && c != '*' && c != '/'){
returnValue = false;
}else{
returnValue = true;
}
return returnValue;
}
}
答案 0 :(得分:0)
如注释中所述,将isNotChar
方法从main方法中删除。之后,您仍然有2个问题。首先是isNotChar
由于if语句的缘故将始终为true。您有:if(c != '+' || c != '-' || c != '*' || c != '/' || c != '^')
。由于您使用||它始终评估为true,您可能打算将它们全部切换为&&
。
您的第二个问题是,您永远不会更新要测试的b1的值。接受新的输入行时,需要在新输入的第一个字符上重新运行isNotChar
,并将b1设置为等于该结果。
答案 1 :(得分:0)
首先,您必须在main方法之外定义isNotChar()方法,因为它是静态上下文,并且是在main方法下定义的。