1

I want to make function which add String into String

I tried like this:

in main fuction

String text = "";
addLine(text, "line1");

in addLine(String text, String line)

text += line;
text += "\n";

I know += operation between String make new instance in java. But, upper code does not work.

How can i make function which add String to String?

조욱재
  • 41
  • 5

2 Answers2

1

I think you want something like this:

  public String addLine(String one, String two){
    return one+two;
}

Note, this returns a string, so in main do something like:

text = addLine(text, "line1");
Tim
  • 561
  • 2
  • 13
0

Make sure you create it as a method:


public class Text {
private String text = "Hello";
public Text(){}
public Text(String text){
    this.text = text;
}
public void setText(String text){
    this.text = text;
}
public void addLine(String lnToAdd){
    text += "\n" +lnToAdd ;
}
public String getText(){
    return text;
}

}


public class Main {

public static void main(String[] args) {

    Text text = new Text("Hello");
    System.out.println(text.getText()); //Returns Hello
    System.out.println();
    text.addLine("Java");
    System.out.println(text.getText()); /*Returns Hello
                                                  Java*/
}

}