我正在编写一个程序,它接受一个字符串并返回一个 boolean 值,指示该单词是否按字母顺序排列,例如abdest、确认、同意等
我的问题是程序没有返回任何输出,只是终止...请进行一些更正,我真的很感激。 这是我的代码:
public class test{
public static boolean Abecedarian(String s) {
String alp="";
for(char c ='A'; c<='Z'; c++){
alp +=c;
}
if(s.equals(alp)){
return true;
}else
return false;
}
public static void main(String[] args) {
Abecedarian("victor");
}
}
最佳答案
试试这个:
public static void main(String[] args) {
String [] words = {"abdest", "acknow", "adempt" };
for (String word : words) {
System.out.println(" isAbecedarian '"+word+"': "+isAbecedarian(word));
}
}
public static boolean isAbecedarian(String s) {
if (s == null ) throw new IllegalArgumentException("Error");
if (s.length() < 2) return true;
char last = s.charAt(0);
char current;
for (int i = 1; i < s.length(); i++) {
current = s.charAt(i);
if (current < last) {
return false;
}
last = current;
}
return true;
}
输出:
isAbecedarian 'abdest': true
isAbecedarian 'acknow': true
isAbecedarian 'adempt': true
关于java - 如果输入的字符串按字母顺序排列,则使用 boolean 方法返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38924228/