2016-11-06 43 views
1

我要讓函數添加字符串轉換成StringJava String - 如何使字符串中添加字符串的功能?

我想是這樣的:

的主要機能的研究

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

在addLine(字符串文本,字符串線)

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

我知道+ = String之間的操作在java中創建新的實例。 但是,上面的代碼不起作用。

我如何使函數將字符串添加到字符串?

+0

什麼不會在'上code'工作? – ItamarG3

回答

1

我想你想是這樣的:

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

注意,這個返回一個字符串,所以在主做這樣的事情:

text = addLine(text, "line1"); 
+0

感謝您的回覆! –

0

請務必將其創建爲一個方法:


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

}

+0

感謝您的回覆! –