使用JAVA

时间:2016-10-01 11:16:29

标签: 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 = 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");
            }
        }

    }
}

4 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

你永远不会在你的阵列中放任何东西。 set.seed(123) result <- df %>% group_by(`column Y`) %>% filter(row_number() %in% sample(seq_len(n()),floor(n()/2))) ##Source: local data frame [5 x 3] ##Groups: column Y [3] ## ## id1 column Y laclen ## <int> <fctr> <int> ##1 9830 A 6 ##2 9922 B 5 ##3 9917 B 8 ##4 9914 C 2 ##5 9914 C 9 只是声明一个长度等于char[] xh = new char[x.length()];的数组,它不会将x的元素设置为xh的元素。相反,使用:

x

您还需要将循环更改为:

char[] xh = x.toCharArray();

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

答案 2 :(得分:1)

你的主要问题是你没有正确地迭代char String,这是最好的方法:

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');

答案 3 :(得分:0)

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

来自评论的

注意,如果没有ed,您必须保留的帐户,这将对字符串的内容进行两次迭代但不是第二个代码,因为第二个例子只是每个

的简短形式
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");
            }
        }
相关问题