Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Aenean pharetra magna ac placerat vestibulum. Purus ut faucibus pulvinar elementum integer enim neque. Iaculis urna id volutpat lacus laoreet non curabitur gravida. Tellus mauris a diam maecenas sed enim ut sem viverra. Pretium lectus quam id leo in vitae turpis. Odio facilisis mauris sit amet massa vitae tortor. Nisl rhoncus mattis rhoncus urna neque viverra justo nec ultrices. Suspendisse faucibus interdum posuere lorem ipsum dolor sit. Tortor at risus viverra adipiscing at in tellus. Egestas quis ipsum suspendisse ultrices gravida dictum fusce ut placerat.
Asked
Active
Viewed 68 times
-1
-
6`char table[]={};` you declared an array of size zero. Code is definitely *not* correct :). Array size doesn't change just because you add stuff to it. Try with an `ArrayList` instead. – Federico klez Culloca Nov 04 '21 at 18:47
3 Answers
5
The problem is char table[] = {}
that is an empty array, then you can't assign value in it, you may need to create it with a size
char[] table = new char[str.length()];
There is a better to do this which is str.toCharArray()
. Also when you return true/false
based on a condition, just return the condition
public static boolean myMethod(String str) {
char[] table = str.toCharArray();
return table[table.length - 1] == 'a' || table[table.length - 1] == 'e';
}
Also Scanner
is a bit easier to use, and if (myMethod(a))
is enough as condition
Scanner in = new Scanner(System.in);
System.out.println("Please enter any word you like:");
String a = in.nextLine();
if (myMethod(a)) {
System.out.println("Word has char 'a' or 'e' at the end of the word.");
} else {
System.out.println("Word doesn't have char 'a' or 'e' at the end of the word.");
}

azro
- 53,056
- 7
- 34
- 70
2
Arrays are of fixed sizes. Your array is essentially of length 0. Try something like
char table[]= new char[str.length()];

dumbPotato21
- 5,669
- 5
- 21
- 34
0
If you must use a for
loop you can use this, which is essentially (now that I look) the same method as azro's except that the toCharArray()
method is explicitly written out as a loop...
if (str == null || str.length() < 1) return false;
char[] chars = new char[str.length()];
for (int i = 0; i < chars.length; i++) chars[i] = str.charAt(i);
return (chars[chars.length - 1] == 'a' || chars[chars.length - 1] == 'e');

scottb
- 9,908
- 3
- 40
- 56