0
System.out.print("Enter a sentence: ");
String sentence = kb.readLine();
int sLength = sentence.length();

if (sentence.charAt(sLength).equals('?')
    System.out.println("Yehey!!!!!");

I'm trying to get the last character and compare it to "?", my code doesn't work. How can I solve the problem?

Maroun
  • 91,013
  • 29
  • 181
  • 233
Rae
  • 81
  • 9

3 Answers3

7

Should be:

sentence.charAt(sLength - 1) == '?'
                        ↑ 
                    Your savior

You need -1 because if the String of length N, then the last character is at place N - 1:

String#charAt:

Returns the char value at the specified index. An index ranges from 0 to length() - 1

Also note that it returns a char, and not a String. Since char is a primitive, you cannot invoke equals, == is just fine.

Maroun
  • 91,013
  • 29
  • 181
  • 233
0

The correct way is:

if (sentence.charAt(sLength-1).equals('?')
        System.out.println("Yehey!!!!!");

Because the last char of a string is ( array.length() - 1 )

Bence Kaulics
  • 6,700
  • 7
  • 31
  • 61
Husseinfo
  • 367
  • 1
  • 9
-1

should be:

       sentence.charAt(sLength - 1) == '?'
thinkinjava
  • 95
  • 1
  • 6