我对代码非常陌生,当我尝试创建带有比较字符的if / else语句时遇到了一个问题。在我尝试编写的代码中,用户正在“赌博”他们是否认为骰子掷骰高于7,低于7或恰好是7。我已经附加了为获取方法编写的代码他们的猜测。当我输入'h','H','l'或'L'时,我收到错误消息,但是当我输入'S'或's'时,该方法可以正常工作。知道为什么吗?预先感谢!
private static char getHighLow(Scanner inScanner) {
System.our.print("High, low or sevens (H/L/S): ");
String str = in.Scanner.nextLine();
char highLow = str.charAt(0);
char highOne = 'h'; char highTwo = 'H'; char lowOne = 'l'; char lowTwo = 'L'; char sevenOne = 's'; char sevenTwo = 'S';
if ((highLow == highOne) | (highLow == highTwo)) {
highLow = 'h';
}
if ((highLow == lowOne) | (highLow == lowTwo)) {
highLow = 'l';
if ((highLow == sevenOne) | (highLow == sevenTwo)) {
highLow = 's';
}
else {
System.out.println("ERROR- enter h, l, or s");
System.out.print("High, low, or sevens (H/L/S): ");
str = in.Scanner.nextLine();
highLow = str.charAt(0);
}
return highLow;
}
答案 0 :(得分:0)
您需要正确放置else
块。更好地使用else if
:
if ((highLow == highOne) | (highLow == highTwo)) {
highLow = 'h';
} else if ((highLow == lowOne) | (highLow == lowTwo)) {
highLow = 'l';
} else if ((highLow == sevenOne) | (highLow == sevenTwo)) {
highLow = 's';
} else {
System.out.println("ERROR- enter h, l, or s");
System.out.print("High, low, or sevens (H/L/S): ");
str = inScanner.nextLine();
highLow = str.charAt(0);
}
您也可以使用开关盒以提高可读性。