Compare a character in a string with a letter?

只谈情不闲聊 提交于 2021-02-05 07:19:04

问题


I want to compare a character in a string with the letter "R". So I want to check if the character on the position i in the string is a "R", a "L" or a "F".

This is my code, but it doesn't word... I'm a Java beginner and really happy about every idea to improve my code and makes it work.

        for (int i = s.length()-2; i >= 0; i--){
            if (s.charAt(i) == "R"){
                    s = s + "L";}
            else if (s.charAt(i) == L){
                    s = s + "R";}
            else {s = s + "F";}

// s = s + s.charAt(i); }//for

By the way, the complete exercise is to get a random string (for example RFFLF), to add a R and then to add the given string in the turned around order and replace (in the added string) every R with L and every L with R.


回答1:


First off, you must be careful with your types. s.charAt(i) returns a char type (not that surprising given the name of the method), but you're comparing it with a String "R". That won't compile and even if it did, it wouldn't work; chars and String are different beasts and are never equal.

char literals are delimited by single quotes, eg 'R'.

This code is what I think you're tying to code:

String result = "";
if (s.charAt(i) == 'R') {
    result = result + "L"; // you could code + 'L' too - both will work
}

Note that your attempt at modifying the original String won't work either. Use a new String as per my code. Much easier to understand and get right.



来源:https://stackoverflow.com/questions/41066085/compare-a-character-in-a-string-with-a-letter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!