Reputation: 21
My goal is to return a string that is composed of each letter as long as the letter is later on in the alphabet than its previous one, assuming the word is lowercase. Problem is, I can't even test this out because I am getting an error (in the title) and I am unsure of how it is occurring. May I have some assistance?
Here is my code:
class Main {
static String alphabetical(String str)
{
String alpha="abcdefghijklmnopqrstuvwxyz";
String betical="";
for(int k=0;k<str.length();k++){
for (int i=0;k<alpha.length();i++){
if(str.charAt(k)>=alpha.charAt(i)){
betical+=str.charAt(k);
}
}
}
return betical;
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(alphabetical("adatplqzh")); //result should be "adtz"
}
}
Upvotes: 2
Views: 99
Reputation: 1
Your inner loop looks wrong,
for (int i=0;k<alpha.length();i++){
should be for (int i=0;i<alpha.length();i++)
Upvotes: 0
Reputation: 5283
As per comment you should change for (int i=0; k< alpha.length(); i++)
to for(int i=0; i< alpha.length(); i++)
and the modify your condition,
if(str.charAt(k)==alpha.charAt(i)){
betical+=str.charAt(k);
}
and it will give the required output
Upvotes: 2