0

I am new coder taking a class over computer science. We are working with Java. The assignment was given through a pdf that I reuploaded as a photo here https://i.stack.imgur.com/xNEdm.png. Here is my code so far.

public class LineEditor {
  private String myLine;

  public void insert(String str, int index) {
    String newmyLine = myLine;
    newmyLine = " world!";
    String sub = myLine.substring(0, index);
    String sub2 = myLine.substring(index, myLine.length()-1);
    System.out.print(sub + str + sub2);
  }

  }
  public void delete(String str) {

  }

  public void deleteAll(String str) {

  }
  public static void main(String[] aghs){
    insert("Hello ", 0);
  }
}

When I run this, I get the error: Cannot make a static reference to the non-static method insert(java.lang.String, int) from the type LineEditor

How can I take the insert method and use it in the main method? If any of my terminology is off, go ahead and tell me as well.

OSG
  • 113
  • 5

1 Answers1

4

main is a static method. You need to create an instance of your class with new and then call insert on it.

Eg:

public static void main(String[] aghs){
  LineEditor le = new LineEditor();
  le.insert("Hello ", 0);
}

The other option you have it to make method static, but having classes with a bunch of static methods can be a sign of bad object-oriented design. Of course this depends on the problem at hand.

rickythefox
  • 6,601
  • 6
  • 40
  • 62