首页 > 解决方案 > error:incomparable types: char and String

问题描述

I was writing a code in hackerearth and got stuck with this problem and getting errors such as:

/hackerearth/JAVA8_5904_0e3a_c5b1_93b1/TestClass.java:13: error: incomparable types: char and String if (directions.charAt(i)=="L"){ ^ /hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:16: error: incomparable types: char and String else if (directions.charAt(i)=="R"){ ^ /hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:20: error: incomparable types: char and String else if (directions.charAt(i)=="U"){ ^ /hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:23: error: incomparable types: char and String else if (directions.charAt(i)=="D"){ ^ 4 errors

Code:

import java.util.*;
import java.io.*;

class TestClass {
    public static void main(String args[] ) throws Exception {
        Scanner scan=new Scanner(System.in);
        String directions=scan.nextLine();
        int length=directions.length();

        int x=0;
        int y=0;
        for (int i=0;i<length;i++){
            if (directions.charAt(i)=="L"){
                x=x-1;
            }
            else if (directions.charAt(i)=="R"){
                x=x+1;

            }
            else if (directions.charAt(i)=="U"){
                y=y+1;
            }
            else if (directions.charAt(i)=="D"){
                y=y-1;
            }
            else
            break;
        }

    }
}

标签: java

解决方案


您使用了双引号 "L" 、 "R" 、 "U" 、 "D" ,这有助于将它们识别为字符串。

请使用单引号让 java 知道它是一个字符。

int x=0;
int y=0;
for (int i=0;i<length;i++){
    if (directions.charAt(i)=='L'){
        x=x-1;
    }
    else if (directions.charAt(i)=='R'){
        x=x+1;

    }
    else if (directions.charAt(i)=='U'){
        y=y+1;
    }
    else if (directions.charAt(i)=='D'){
        y=y-1;
    }
    else
        break;
}

}   

}


推荐阅读