4

I need to write a Java program that reads a string and determines if there are these two letters: the lowercase letter “e” or “d”.

That's what i written so far! any ideas why this doesn't work?

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

    }
}
Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
noel293
  • 466
  • 4
  • 18

4 Answers4

1

First you have an ArrayOutOfBound exception because you need to stop just before the length, i.e. i<x.length().

Now your problem is that you test against an array of char that is full of null chars. You need to test against the string :

if (x.charAt(i) == e || x.charAt(i) == d) {
Jean-Baptiste Yunès
  • 30,872
  • 2
  • 40
  • 66
1

You never put anything in your array. char[] xh = new char[x.length()]; simply declares an array of length equal to x, it does not set the elements of xh to the elements of x. Instead, use:

char[] xh = x.toCharArray();

You also need to change your loop to:

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

to avoid the out of bounds exception you are currently seeing.

nhouser9
  • 6,572
  • 3
  • 18
  • 39
  • Calling `toCharArray()` will work but it is not a best approach here as it will create new character array which is useless here as we only need to read the content of the `String` – Nicolas Filotto Oct 01 '16 at 11:46
1

Your main problem is the fact that you don't properly iterate over the char of your String, here is the best way to do it:

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

Assuming that you use Java 8, you could rely on the Stream API to do the same thing as next:

boolean result = x.chars().anyMatch(c -> c == 'e' || c == 'd');
Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
0

this is the simple solution if you want to use it

NOTE from comments, you must keep account that if there is no e and d, this will iterate twice on the content of the String but not is second code as second example is just short form of for each

String str = "ewithd";
        if (str.contains("e") || str.contains("d")) {
            System.out.println("sucess");
        } else
            System.out.println("fail");

if you want to go with array then you can use foreach() too

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