Coulter Heiberger
Coulter Heiberger

Reputation: 3

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

    }

    }
}

Upvotes: 0

Views: 239

Answers (3)

FredK
FredK

Reputation: 4084

Another way:

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

Upvotes: 3

nissim abehcera
nissim abehcera

Reputation: 831

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

with

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

Upvotes: 2

John Bollinger
John Bollinger

Reputation: 181824

This ...

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

... does not make sense. The operands of the || operator need to be booleans. 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 Strings like any other, on which you can invoke methods. Such as indexOf():

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

Upvotes: 2

Related Questions