2014-01-23 244 views
-1
String firstname , middlename , lastname ; 

firstname = fn.getText().substring(0,1); 
middlename = mn.getText().substring(0,1); 
lastname = ln.getText(); 

String shortname = shortname.concat(lastname); // error is in this line, shortname.concat 

shortname = shortname.concat(" "); 
shortname = shortname.concat(firstname); 
shortname = shortname.concat("."); 
shortname = shortname.concat("middlename"); 
shortname = shortname.concat("."); 

shrt.setText(shortname); 

没有其他行有任何错误。只是shortname变量未初始化。变量未被初始化

注:易于解决方案请。我在第11课。做这个JAVA没有文字书。

+0

请编辑您的文章,并附上错误[stack trace](http://en.wikipedia.org/wiki/Stack_trace) – Christian

+0

@Christian,这是一个编译错误;) –

回答

0

你正试图使用​​shortname甚至在声明它之前。你需要声明它并在使用它之前初始化一个变量。在RHS上使用shortname意味着你甚至在LHS上声明之前就试图使用它。首先声明并初始化它,然后使用它。

String shortname = ""; // blank string, for initializing it 
shortname = shortname.concat(lastname); 

由于@Brian曾评论说,如果它的将是一个空白字符串CONCAT,你还不如干脆直接赋值给它。这样你就不需要2条语句。

String shortname = lastname; // Declaration and initialization, done! 
+1

谢谢大家,它做的工作。 –

0

用途:

String shortname = ""; 
    shortname = shortname.concat(lastname); 
+0

为什么concat在我们知道的时候它是空的?字符串shortName = lastname –

+0

完全不需要连接空字符串 – Aarav

5

右手表达

String shortname = shortname.concat(lastname); 

将之前评估分配,所以当你尝试做

shortname.concat(lastname) 

shortname那时没有初始化。为了解决这个问题,你必须使用空字符串("")使用前初始化

String shortname = ""; 
shortname = shortname.concat(...); 

编辑:

由于@BrianRoach评论说,没有必要来连接它,因为你只是将一个空字符串("")与另一个String连接起来。只是做:

String shortname = lastname; 
+2

为什么concat在我们知道它是空的时候?'String shortName = lastName' –

+0

你是对的,我忽略了它。编辑。 – Christian

+0

@BrianRoach:好点 –

0

用来初始化SHORTNAME第一

Actulally shortname doesnt contain anything to concat with. 

所以提供一些价值吧,

String shortname=""; 
shortname = shortname.concat(lastname); 

编辑:

如@BrianRoach在@Christians解答发表了评论,我们应该用来初始化短名称。 as

String shortname=lastname; 

来评估串联的目的。

+0

@BrianRoach:通过在Christian的回答中看到您的评论,我已经在进行编辑。 –

+0

我刚刚发表了同样的评论,他们所有;) –

+0

好吧,好点虽然:) –