开发者

Why am I getting an incompatible types error when trying to see if a String ends with a specific character?

开发者 https://www.devze.com 2023-03-03 12:09 出处:网络
I\'m working on a dinky code for java, in which I have to create a program that: 1) capitalizes the first word of the input sentence, 2) capitalizes the word \"I\", and 3)punctuates the sentence if th

I'm working on a dinky code for java, in which I have to create a program that: 1) capitalizes the first word of the input sentence, 2) capitalizes the word "I", and 3)punctuates the sentence if there is no proper punctuation. I wrote the code easily, but 开发者_StackOverflow中文版it's a bit messy. Specifically, I was wondering how you would use a special character for a conditional.

for example,

String sentence = IO.readString(); /* IO.readstring is irrelevant here, it's just a           scanning class that reads a user input*/
int length = sentence.length();
char punctuation = sentence.charAt(length - 1);
if (punctuation != "." || punctuation != "?" || punctuation != "!")
    {
        sentence = sentence + ".";
    }

this is giving me an incompatible types error when I try to compile it (incompatible types : char and java.lang.string)

How would I go about writing this conditional?


When you use "" that implies a String. For characters, use '.' (the single quote).


Use single quote for characters in java:

if (punctuation != '.' || punctuation != '?' || punctuation != '!')

I haven't checked your logic since question was not entirely clear to me.


Literal characters are delimited by single quotes: 'x'.

Literal strings are delimited by double quotes: "x".

Characters are primitives, while strings are object (of the java.lang.String class), and you cannot compare primitives to objects.


A short hand for checking multiple characters is to use String.indexOf

if (".?!".indexOf(punctuation) < 0)
    sentence += '.';
0

精彩评论

暂无评论...
验证码 换一张
取 消