【发布时间】:2019-02-26 22:41:34
【问题描述】:
我正在编写一个程序,它将确定双文字是否为 4 个字符,并将其打印在屏幕上。我相信我做了正确的部分,我将检查是否正好有 4 个字符。我被困在如何检查 +、- 或 .是第一个字符。和我的
str.charAt(0) == "+" || "-" || "." 我收到一个不兼容的操作数错误。
public class Program4 {
public static void main(String[] args) {
Scanner stdIn = new Scanner(System.in);
String str;
System.out.println("Please enter a valid (4 character) double literal consisting of these numbers and symbols: '+', '-', '.', (decimal point), and '0' through '9'");
str = stdIn.nextLine();
int length = str.length();
// the next if statement will determine if there are exactly 4 characters \\
if ( length == 4 ) {
// the next if statement checks for a +, -, or . (decimal) in the first character \\
if ( str.charAt(0) == "+" || "-" || ".") {
}
}
else {
System.out.println ("Please restart the program and enter in a valid 4 character double literal.");
}
}
}
【问题讨论】:
-
if ("+-.".indexOf(str.charAt(0)) >= 0) { -
str.charAt(0) == '+' || str.charAt(0) == '-' || str.charAt(0) == '.' -
这不是 COBOL;你不能做像
x == a || b || c这样的“捷径”布尔运算。您必须完整地写出每个比较:x == a || x == b || x == c -
String#startsWith
标签: java if-statement