如何检查字符串是否带有+,-或。 (十进制)的第一个字符?

时间:2019-02-26 22:41:35

标签: java if-statement

我正在编写一个程序,该程序将确定双精度文字是否为4个字符,并将其打印在屏幕上。我相信我做的正确,我将检查是否有4个字符。我被困在如何检查+,-或。是第一个字符。和我的 Excel Source我收到一个不兼容的操作数错误。

str.charAt(0) == "+" || "-" || "."

3 个答案:

答案 0 :(得分:3)

另一种方式:

switch ( str.charAt(0) ) {
  case '+': case '-': case '.':
    <do something>
    break;
}

答案 1 :(得分:2)

替换此if ( str.charAt(0) == "+" || "-" || ".") {

使用

`if ( str.charAt(0) == '+' || str.charAt(0)=='-' || str.charAt(0)=='.') {

答案 2 :(得分:2)

这个...

    if ( str.charAt(0) == "+" || "-" || ".") {

...没有意义。 ||运算符的操作数必须为boolean s。表达式str.charAt(0) == "+"的计算结果为boolean,但两个独立的字符串却不然。

有很多方法可以解决此问题,哪种方法对您最有意义取决于上下文。但是,一种处理方法是使用这样的事实,即字符串文字与任何其他字符串一样String,可以在其上调用方法。例如indexOf()

if ("+-.".indexOf(str.charAt(0)) >= 0) {
    // starts with +, -, or .
}