繁体   English   中英

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

[英]How can I check if a string has +, -, or . (decimal) in the first character?

我正在编写一个程序,该程序将确定双精度文字是否为4个字符,并将其打印在屏幕上。 我相信我做的正确,我将检查是否有4个字符。 我被困在如何检查+,-或。 是第一个字符。 用我的str.charAt(0) == "+" || "-" || "." 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.");

    }

    }
}

其他方式:

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

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

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

这个 ...

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

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

解决此问题的方法有很多,而哪种方法最适合您取决于上下文。 但是, 一种解决方法是使用一个事实,即字符串文字与其他String一样都是String ,可以在其上调用方法。 indexOf()

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM