类似的代码,但一个版本在应该的时候没有 return a String
Similar code, yet one version does not return a String when it should
对于 class 练习,我和我的朋友都编写了类似的代码。她的有效,而我的无效:
错误:此方法必须 return 类型为 java.lang.String
的结果
她的密码:
public static String alphaString (String a, String b) {
for (int i=0; i<a.length(); i++){
if ((int)(a.charAt(i)) < ((int)(b.charAt(i)))) {
return a;
}
if ((int)(a.charAt(i)) > ((int)(b.charAt(i)))) {
return b;
}
}
return ("these are the same words") ;
}
我的代码:
// 采用两个字符串的方法,return 是字母表中第一个
// alphaString("banana", "apple")--> "apple"
// alphaString("snake", "squirrel")--> "snake".
public static String alphaString(String s1, String s2) {
for (int i = 0; i<s1.length(); i++ ) {
if (s1.charAt(i)<s2.charAt(i)) {
return s1;
}
if (s1.charAt(i)>s2.charAt(i)){
return s2;
}
}
现在,我可以看出我们的变量命名不同,而且她使用 (int)(尽管我认为没有必要)。我不明白为什么她的代码有效而我的无效。如果我也尝试添加 (int) 并使代码更加相似,我仍然会收到错误消息。
有人知道为什么会这样吗?
您似乎缺少"these are the same words"
的默认值 return。不清楚为什么你们都选择用循环来实现它(或者为什么你们都不选择使用 else
)。无论如何,String
是 Comparable
所以我会简单地做
public static String alphaString(String s1, String s2) {
int c = s1.compareTo(s2);
if (c < 0) {
return s1;
} else if (c > 0) {
return s2;
}
return "these are the same words";
}
对于 class 练习,我和我的朋友都编写了类似的代码。她的有效,而我的无效:
错误:此方法必须 return 类型为 java.lang.String
的结果她的密码:
public static String alphaString (String a, String b) {
for (int i=0; i<a.length(); i++){
if ((int)(a.charAt(i)) < ((int)(b.charAt(i)))) {
return a;
}
if ((int)(a.charAt(i)) > ((int)(b.charAt(i)))) {
return b;
}
}
return ("these are the same words") ;
}
我的代码:
// 采用两个字符串的方法,return 是字母表中第一个
// alphaString("banana", "apple")--> "apple"
// alphaString("snake", "squirrel")--> "snake".
public static String alphaString(String s1, String s2) {
for (int i = 0; i<s1.length(); i++ ) {
if (s1.charAt(i)<s2.charAt(i)) {
return s1;
}
if (s1.charAt(i)>s2.charAt(i)){
return s2;
}
}
现在,我可以看出我们的变量命名不同,而且她使用 (int)(尽管我认为没有必要)。我不明白为什么她的代码有效而我的无效。如果我也尝试添加 (int) 并使代码更加相似,我仍然会收到错误消息。
有人知道为什么会这样吗?
您似乎缺少"these are the same words"
的默认值 return。不清楚为什么你们都选择用循环来实现它(或者为什么你们都不选择使用 else
)。无论如何,String
是 Comparable
所以我会简单地做
public static String alphaString(String s1, String s2) {
int c = s1.compareTo(s2);
if (c < 0) {
return s1;
} else if (c > 0) {
return s2;
}
return "these are the same words";
}