简体   繁体   中英

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

I am writing a program that will determine if a double literal is 4 characters, and print it out on the screen. I believe I did the part right where I will check to see if there are exactly 4 characters. I am stuck on how to check if a +, - or . is the first character. With my str.charAt(0) == "+" || "-" || "." str.charAt(0) == "+" || "-" || "." I am receiving an Incompatible operand error.

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.");

    }

    }
}

Another way:

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

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

with

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

This ...

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

... does not make sense. The operands of the || operator need to be boolean s. The expression str.charAt(0) == "+" evaluates to a boolean , but the two strings standing by themselves do not.

There are numerous ways to solve this problem, and which one makes the most sense for you depends on context. However, one way to go about it uses the fact that string literals are String s like any other, on which you can invoke methods. Such as indexOf() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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