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