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

Read 2 letters in a string using JAVA

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

你永远不会在你的数组中放任何东西。 char[] xh = new char[x.length()]; 只是声明一个长度等于x 的数组,它不会将xh 的元素设置为x 的元素。相反,使用:

char[] xh = x.toCharArray();

您还需要将循环更改为:

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

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

您的主要问题是您没有正确迭代 Stringchar,这是最好的方法:

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

假设您使用 Java 8,您可以依靠 Stream API 来执行与下一个相同的操作:

boolean result = x.chars().anyMatch(c -> c == 'e' || c == 'd');

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

注意 来自评论,你必须记下 如果没有 ed,这将迭代两次String 的内容但不是第二个代码,因为第二个示例只是每个

的缩写形式
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");
            }
        }