gpt4 book ai didi

java - 使用JAVA读取字符串中的2个字母

转载 作者:搜寻专家 更新时间:2023-11-01 02:59:31 24 4
gpt4 key购买 nike

我需要编写一个 Java 程序来读取一个字符串并确定是否存在这两个字母:小写字母“e”或“d”。

这就是我到目前为止所写的!有什么想法为什么这不起作用吗?

class ex2 {
public static void main(String[] args) {
//boolean arg1;
char e = 'e';
char d = 'd';
String x = "This is my test";
char[] xh = new char[x.length()];
for(int i=0; i<= x.length();i++) {
if (xh[i] == e || xh[i] == d) {
// arg1 = true;
System.out.println("Correct"); // Display he string
} else {
//arg1 = false;
System.out.println("Wrong");
}
}

}
}

最佳答案

首先你有一个ArrayOutOfBound异常,因为您需要在长度之前停止,即 i<x.length() .

现在您的问题是您要针对 char 的数组进行测试充满了空字符。您需要针对字符串进行测试:

if (x.charAt(i) == e || x.charAt(i) == d) {

关于java - 使用JAVA读取字符串中的2个字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39805932/

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