-1

How do I call the method convertName in main? When i tried other ways, it came up with the error cannot reference non static method from static area.

/*
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;   
    }

    }
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
Alex C
  • 13
  • 3
  • 1
    Make `convertName` a `static` method. – August Oct 14 '14 at 22:37
  • 2
    @August While that would work, it doesn't offer any insight as to *why* it works. At any rate, this is a duplicate of one of many, many similarly themed questions... – JonK Oct 14 '14 at 22:38

1 Answers1

3

Because the method isn't static, you need an instance of Name.

String str = "some string";
new Name().convertName(str);

Or, change

public String convertName(String name) {

to

public static String convertName(String name) {

Then in main()

String str = "some string";
convertName(str); // <-- calling a static method doesn't need an instance.
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249