0
Assignment help.
(Java) Hi everyone, I'm currently learning Java at my high school. We've covered only primitive types, using objects, if statements, and iteration. (I have not learned about array or chartAt yet) The teacher asks us to write a method that would return true if the characters in the String are in alphabetical order and false if not. Could you guys please help me with this ? For example: input: Zoo, output: false (since the characters in the String ”Zoo” is not in alphabetical order) input: abc, output: true (since the characters in the String ”abc” is in alphabetical order)
6 Antworten
0
thanks. But since I don't know what the words that are being checked. Could you please tell me other methods that I can also apply to compare them? My teacher told us all the words will be lowercase. I’m sorry if this is a stupid question, I'm new to coding
+ 6
Hello Suni Hoang Anh
Char is an interesting data type because you can thread it like integers (because of its ascii values). You only need to make sure that all letters have the same case.
a < b will return true because 97 < 98
z < s returns false because 122 > 115
String has a method toLowerCase(). For example
"Zoo".toLowerCase() returns "zoo".
(toUpperCase() would also work: "hello" would become "HELLO")
charAt(index i) returns the char of a string at a specific index.
Like arrays the first index is 0, the last index is at length() - 1
"hello".charAt(0) returns 'h'
"help".charAt(2) returns 'l'
So you can use a for loop to compare each char with the next char:
yourWord.charAt(0) > yourWord.charAt(1) return false (not alphabetical)
else compare charAt(1) with charAt(2) and so on...
Hope this helps.
+ 4
Like with integers you can use <, >, ==, <= and >= for char comparing.
+ 4
No, I don't think there are other methods. And I think using < and > is the easiest way.
This is how I would write the method:
public static boolean isAlphabetical(String word){
for(int i = 0; i < word.length() - 2; i++){
if(word.charAt(i) > word.charAt(i + 1) return false;
}
return true;
}
+ 1
thank you so much. I really appreciate it
0
thank you so much for your response. But can you please explain to me more about comparing char with the next char? I don’t quite get that