//getFirstName method
public String getFirstName()
{
String firstName = name.substring(0, name.lastIndexOf(' '));
return firstName;
}
//getLastName method
public String getLastName()
{
String lastName = name.substring(name.lastIndexOf(" ")+1);
return lastName;
}
//alphaName method :: returns a String of the users's full name
//in alphanumeric order; returns a String with first and last named switched,
//only if necessary; instance variable name is left unchanged
// use the String class compareTo() method
public String alphaName()
{
String compare = firstName.compareTo(lastName);
if(compare < 0){
return getFirstName() + getLastName();
}
else if(compare > 0){
return getLastName() + getFirstName();
}
else{
return getLastName() + getFirstName();
}
return compare;
}
您好,我无法弄清楚如何按字母数字顺序编写代码。我现在有这个,并且不能正确输出。我没有添加整个程序,但这应该足够了。我使用了compare,抓住了方法getFirstName和getLastName,但输出不正确。请帮忙,谢谢!
答案 0 :(得分:2)
compareTo应该返回一个整数,而不是字符串-您正尝试将其存储到字符串而不是整数中。将其更改为“ int compare”,它应该可以工作。
答案 1 :(得分:-1)
尝试一下-
public String alphaName(String firstName, String lastName)
{
int compare = firstName.compareTo(lastName);
if(compare < 0){
return firstName + " " + lastName;
}
else if(compare > 0){
return lastName + " " + firstName;
}
else{
return lastName + " " + firstName;
}
}