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
  • 94,125
  • 30
  • 188
  • 241
Rae
  • 83
  • 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
  • 94,125
  • 30
  • 188
  • 241
  • 1
    "arrays are zero-based" <-- not really; if a `String` is a char array, `.charAt()` is specified by `CharSequence` – fge Dec 01 '14 at 13:44
  • Which is backed up with array, no? – Maroun Dec 01 '14 at 13:45
  • ohhh!!!! great!!! i hadnt known about it!!! thank you so much... actually you are my savior... so basically what does -1 mean??? – Rae Dec 01 '14 at 13:46
  • No, it doesn't have to be. [this project](https://github.com/fge/largetext) implements `CharSequence`, for instance, and is not backed by an array – fge Dec 01 '14 at 13:46
  • @Rae It means minus one, if your string is "hello_world", then "d" is at the 10th place. – Maroun Dec 01 '14 at 13:46
  • @MarounMaroun , i see because in counting characters it starts with 0??? – Rae Dec 01 '14 at 13:48
  • @MarounMaroun great!!!! i learn something now!!! thank you so much.... :D have a nice day ahead – Rae Dec 01 '14 at 13:50
  • @Rae , You should then accept this answer as it answered your question – Spikatrix Dec 01 '14 at 13:52
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
  • 7,066
  • 7
  • 33
  • 63
Husseinfo
  • 472
  • 2
  • 9
-1

should be:

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