gpt4 book ai didi

java - 错误:incomparable types: char and String

转载 作者:行者123 更新时间:2023-12-02 00:04:47 25 4
gpt4 key购买 nike

我正在 hackerearth 中编写代码,并遇到了这个问题并收到如下错误:

/hackerearth/JAVA8_5904_0e3a_c5b1_93b1/TestClass.java:13:错误:无法比较的类型:char 和 String if (directions.charAt(i)=="L"){ ^/hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:16:错误:无法比较的类型:char 和 String else if (directions.charAt(i)=="R"){ ^/hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:20:错误:无法比较类型:char 和 String else if (directions.charAt(i)=="U"){ ^/hackerearth/JAVA8_4249_518a_8275_14e5/TestClass.java:23:错误:无法比较的类型:char 和 String else if (directions.charAt(i) ==“D”){ ^ 4 个错误

代码:

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;
}

}

}

关于java - 错误:incomparable types: char and String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58162158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com