user2789945
user2789945

Reputation: 565

Checking a String in an array for brace (java)

so i'm currently trying to check whether or not there's a brace in a String in an array, but I can't figure out how its done.

    public void braceChecker()
    {
         String[] code = new String[]{"{} [] () {"};         
         System.out.println(code[0].charAt(0) == "{");
    }

Obviously, it errors on the last print statement, but I can't find a way to check that character without java yelling at me. If I take "{" out of the string, it interprets it as an actual brace. How do I go about this?

Upvotes: 0

Views: 111

Answers (4)

baeda
baeda

Reputation: 191

A char is compared to by using single quotes ' not double quotes " which are used for Strings.

public void braceChecker()
{
     String[] code = new String[]{"{} [] () {"};
     System.out.println(code[0].trim());
     System.out.println(code[0].charAt(0) == '{');
}

Upvotes: 0

shree.pat18
shree.pat18

Reputation: 21757

Change it to single quotes to compare as a character.

Upvotes: 0

betteroutthanin
betteroutthanin

Reputation: 7586

Use

System.out.println(code[0].charAt(0) == '{');

instead, "" is a String

Upvotes: 1

NPE
NPE

Reputation: 500733

Change the "{" to '{' (your want a character literal, not a string literal).

See Character and String Literals in the tutorial.

Upvotes: 3

Related Questions