【发布时间】:2013-12-02 12:50:42
【问题描述】:
如果第一个字符串按字典顺序大于第二个字符串,则返回 1,如果相等则返回 0,否则返回 -1。在某些情况下正确返回 1,-1,0,但对于此 str1 和 str2,返回结果与期望的输出相反。
public class StringCompare {
static String testcase1 = "helloworld";
static String testcase2 = "hellojavaworld";
public static void main(String args[]) {
StringCompare testInstance = new StringCompare();
int result = testInstance.newCompare(testcase1, testcase2);
System.out.println("Result : " + result);
}
// write your code here
public int newCompare(String str1, String str2) {
int l1 = str1.length();
int l2 = str2.length();
int max = 0;
if (l1 <= l2) {
max = l1;
}
else
max = l2;
int count = 0;
for (int i = 0; i < max; i++) {
char ch1 = str1.charAt(i);
char ch2 = str2.charAt(i);
if (str2.charAt(i) > str1.charAt(i)) {
return - 1;
}
if (str1.charAt(i) > str2.charAt(i)) {
return 1;
}
if (l1 == l2) {
if (ch1 == ch2) {
count++;
}
if (count == max) {
return 0;
}
}
}
if (l1 == l2) return 0;
if (l1 > l2)
return 1;
else
return - 1;
}
}
【问题讨论】:
-
缩进....
-
我在提交之前按 ctrl+k...
-
你试过调试了吗?
-
如果你能指出什么 cales 给出了不正确的输出,那就太好了。
-
您在问题中给出的代码在字典顺序方面是正确的;看来您对“所需输出”的定义不匹配。
hello < hi因为e < i。换句话说,比较hello和hi得出的结果与比较he和hi的结果相同。这是正确的。
标签: java