Write a method header on line two with the following specs:
Returns: a String Name: alphabetical Parameters: a String called str Purpose: Return a string that is composed of each letter as long as the letter is later on in the alphabet than its previous one. You can assume actual parameters are lowercase. See below examples. |
Additional Info:
You can use < and > to compare characters (not Strings), where characters later on in the alphabet are "greater". Examples:
- 'a' < 'b' ==> True
- 'a' < 'a' ==> False
- 'a' > 'b' ==> False
Examples:
- alphabetical("abczef") ==> "abcz"
- alphabetical("adatplqzh") ==> "adtz"
- alphabetical("dbeuptvwmy") ==> "deuvwy"
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
class Main {
public static String alphabetical(String s)
{
s=s.toLowerCase();
char max=s.charAt(0);
String result=String.valueOf(s.charAt(0));
for(int i=1;i<s.length();i++) {
if(max<s.charAt(i)){
result+=String.valueOf(s.charAt(i));
max=s.charAt(i);
}
}
return (String)result;
}
//test case below (dont change):
public static void main(String[] args){
System.out.println(alphabetical("adatplqzh"));//"adtz"
System.out.println(alphabetical("abczef"));// "abcz"
System.out.println(alphabetical("dbeuptvwmy"));// "deuvwy"
}
}
|
반응형
'Java_beginner(Repl.it) > Auto-Graded-Course(AP CS A)' 카테고리의 다른 글
054 - Accumulator Method String Practice 2 (0) | 2019.12.26 |
---|---|
053 - Accumulator Method String Practice 1 (0) | 2019.12.26 |
051 - Accumulator Method Challenge 1 (optional) (0) | 2019.12.26 |
050 - Accumulator Method Practice 6 (0) | 2019.12.26 |
049 - Accumulator Method Practice 5 (0) | 2019.12.26 |