How to make fuction which add String into String?

This question already has an answer here:

  • Passing a String by Reference in Java? 13 answers
  • How do I concatenate two strings in Java? 19 answers

  • 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");
    

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

    }

    链接地址: http://www.djcxy.com/p/20882.html

    上一篇: 按参考对象与按值参照

    下一篇: 如何使字符串添加到字符串功能?