如何在main中调用convertName方法? 当我尝试其他方式时,它出现了错误 不能从静态区域引用非静态方法。
/*
This program will take a name string consisting of EITHER a first name followed by a last name
(nonstandard format) or a last name followed by a comma then a first name (standard format).
Ie. “Joe Smith” vs. “Smith, Joe”. This program will convert the string to standard format if
it is not already in standard format.
*/
package name;
public class Name {
public static void main(String[] Args){
boolean flag1 = hasComma ("Alex Caramagno");
}
public static boolean hasComma(String name) {
// indexOf will return -1 if a comma is not found
return name.indexOf(',') >= 0;
}
public String convertName(String name) {
if (hasComma(name)) {
return name;
}
int index = name.indexOf(' ');
String first = name.substring(0, index);
String last = name.substring(index+1);
String convertedName = last + ", " + first;
return convertedName;
}
}
答案 0 :(得分:3)
由于该方法不是static
,因此您需要Name
的实例。
String str = "some string";
new Name().convertName(str);
或者,改变
public String convertName(String name) {
到
public static String convertName(String name) {
然后在main()
String str = "some string";
convertName(str); // <-- calling a static method doesn't need an instance.