使用JAVA阅读字符串中的两个字母

使用JAVA阅读字符串中的两个字母,java,string,chars,Java,String,Chars,我需要编写一个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

我需要编写一个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");
            }
        }

    }
}
类ex2{
公共静态void main(字符串[]args){
//布尔arg1;
字符e='e';
chard='d';
String x=“这是我的测试”;
char[]xh=新字符[x.length()];

对于(int i=0;i首先,您有一个
ArrayOutOfBound
异常,因为您需要在长度之前停止,即
i您从未在数组中放入任何内容。
char[]xh=new char[x.length()];
只声明一个长度等于
x
的数组,它不会将
xh
的元素设置为
x
的元素

char[] xh = x.toCharArray();
您还需要将循环更改为:

for(int i=0; i < x.length(); i++) {
for(int i=0;i

为了避免您当前看到的越界异常。

您的主要问题是没有正确地迭代
字符串的
字符,下面是最好的方法:

for (int i = 0, length = x.length(); i < length; i++) {
    char c = x.charAt(i);
    ...
}

如果您想使用它,这是一个简单的解决方案


注意从注释中,您必须注意,如果没有
e
d
,这将在字符串内容上迭代两次,但不是第二个代码,因为第二个示例只是每个字符串的简短形式

String str = "ewithd";
        if (str.contains("e") || str.contains("d")) {
            System.out.println("sucess");
        } else
            System.out.println("fail");
如果要使用数组,也可以使用
foreach()

char[] ch = str.toCharArray();
        for (char c : ch) {
            if (c == 'e' || c == 'd') {
                System.out.println("success");
            else
                System.out.println("fail");
            }
        }

1.您应该获得ArrayOutOfBoundsException,因为您的for循环不应执行相等性检查2.您的xh数组为空i do…在打印完所有“错误”后,我也会得到该异常..有什么想法吗?使用char xh[]=x.ToCharray();这就是在调试器中单步执行代码可以显示问题所在的地方。调用
toCharArray()
会起作用,但这不是最好的方法,因为它会创建新的字符数组,这在这里是无用的,因为我们只需要读取
字符串的内容。如果没有
e
d
,这将在
字符串的内容上重复两次。nicolasFilotto感谢您指出,我将把副词放在这里我也是……)
String str = "ewithd";
        if (str.contains("e") || str.contains("d")) {
            System.out.println("sucess");
        } else
            System.out.println("fail");
char[] ch = str.toCharArray();
        for (char c : ch) {
            if (c == 'e' || c == 'd') {
                System.out.println("success");
            else
                System.out.println("fail");
            }
        }