我对代码很陌生,当我尝试创建带有比较字符的 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;
}
您需要正确放置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);
}
您还可以使用开关大小写以获得更好的可读性。