【问题标题】:How can I check if a string has +, -, or . (decimal) in the first character?如何检查字符串是否有 +、- 或 . (十进制)在第一个字符?
【发布时间】: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


【解决方案1】:

另一种方式:

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

【讨论】:

    【解决方案2】:

    这...

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

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

    解决这个问题的方法有很多,哪一种对您最有意义取决于具体情况。然而,one 方法使用了这样一个事实,即字符串文字是 Strings 和其他任何东西一样,您可以在其上调用方法。如indexOf()

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

    【讨论】:

    • 您没有解决代码的另一个问题,即将char 与字符串文字而非字符文字进行比较。
    【解决方案3】:

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

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

    【讨论】:

    • 仍然是无效的 Java 语法,因为你不能说 a == 1 || 2 || 3
    • 显然-----
    猜你喜欢
    • 2012-07-20
    • 2012-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多