java - 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;
}
}
}
解决方案
您使用了双引号 "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;
}
}
}
推荐阅读
- linux - 如何在linux中获取连接的局域网客户端的主机名
- laravel - 森南支付首次登出
- javascript - 如何在 vuejs 中的页面加载时启动 Bootstrap 模式?
- spring - 在 swagger-ui.js 实现中添加 info 对象
- openshift - Minishift 列出所有目录项
- arrays - 传递数组元素的地址不工作 - C - 我做的方式
- sql - 内部 SELECT 语句是否可以被 JOIN 语句替换?
- ios - 快速检查是否包含视频内容的 zip 文件
- user-controls - UC 是我的 GoTo,还是有更好的方法?
- sql-server - 在 Microsoft SSMS 中导入 XLXS