2010-11-19 69 views
1

我想在运行时追加一个字符串,但此代码再次添加上一个单词而不是追加新单词。在字符串中追加文本

Customer.java:

public String getCustomerQuestion() { 
    return CustomerQuestion; 
} 
public void setCustomerQuestion(String customerQuestion) { 
CustomerQuestion = customerQuestion; 
} 
public void appendmessage(String msg){ 
CustomerQuestion = CustomerQuestion +" "+ msg; 
} 

Main.java:

Customer _Customer =new Customer(); 
Request_Message Request= new Request_Message; 
_Customer.setCustomerQuestion(Request.getInput()); 
String _string=Request.getInput(); 
_Customer.appendmessage(_string); 
String str=__Customer.getCustomerQuestion(); 
System.out.println("now new Question() is"+str); 

当我将RAM写入,然后按当我写这辛格结果显示后再次进入:在控制台砣砣。 我想显示ram singh作为一个字符串。 `public class Request_Message { {0}私人String _Input;

public void setInput(String line) { _Input = line; } public String getInput() { return _Input; }`

它需要从聊天窗口输入。

+0

有没有这样的对象作为'__Customer'?实例变量的命名方案也很奇怪。大写字母? – 2010-11-19 08:07:51

+0

为什么在示例中的其他任何地方使用_Customer时,您在名为_ITChatParticipant的对象上使用getCustomerQuestion?这是一个错字吗? – Erik 2010-11-19 08:09:19

回答

0

请勿使用字符串连接。改为使用适当的StringBuffer

private StringBuffer customerQuestion = new StringBuffer(); 

public void appendmessage(String msg){ 
    customerQuestion.append(msg); 
} 

public String getCustomerQuestion() { 
    return customerQuestion.toString(); 
} 

当然,这可能不是你的具体问题的原因(为此事看乔恩斯基特的答案),但是这可能是未来的一个瓶颈。 A StringBuffer是使用String并将文本串联起来的正确方法。

+2

这是不是很清楚,这是否合适,并且不能解释OP所看到的行为。 – 2010-11-19 08:08:24

+0

最好在删除这篇文章之前,有人来推荐'StringBuilder'。 ;) – 2010-11-19 09:01:59

+0

字符串串联在这个应用程序中是一个“瓶颈”,肯定会成为OPs问题中最小的问题 – fish 2010-11-19 10:41:26

2

您还没有显示什么Request.getInput()做什么。我嫌疑人这就是问题所在。如果运行会发生什么:

System.out.println(Request.getInput()); 
System.out.println(Request.getInput()); 

并输入两个不同的字符串?

如果你可以发布一个简短的,但是完整的程序,我们可以肯定会发生什么事情。

(在一个侧面说明,如果按照正常的Java命名约定,它很可能是其他人更容易跟随你的代码。)

+0

它只打印第一个字符串。它不需要第二个string.please帮助.. – singh 2010-11-19 08:51:43

+0

@singh:这很难提供帮助,因为这显然是'Request.getInput()'中的一个问题,并且你根本没有给我们提供任何信息* 。 – 2010-11-19 09:19:38