今天我做一个Assignment,在我的程式中有这么一段
--------------------------------------------------------------------------------------
String[] lineOfTexts = text.split( "\\n" );
for( int i = 0; i < lineOfTexts.length; i++ ) {
int lineNum = i + 1;
String[] words = lineOfTexts[i].toLowerCase().split( "\\s+" );
System.out.println( words.length );
for( int j = 0; j < words.length; j++ ) {
if( words[j].endsWith( "-" ) ) {
words[j] = words[j].replaceAll( "[^a-z]", "" );
frontWord = words[j];
} else if( j == 0 && frontWord != "" ) {
words[j] = words[j].replaceAll( "[^a-z]", "" );
frontWord = frontWord.concat( words[j] );
records.addRecord( frontWord, 1, lineNum - 1 );
frontWord = "";
} else {
words[j] = words[j].replaceAll( "[^a-z]", "" );
records.addRecord( words[j], 1, lineNum ); }
} // end internal loop
} // end external loop
--------------------------------------------------------------------------------------
首先text是一个String类型变量,它的值是从一个plain text file中打开获得的(文本读入ok的,没问题的)。问题出在当我用的文本文件为空时,lineOfTexts.length = 1(我验证过的,但为什么不时0?郁闷在这里), 而当我在空文本中打入几个回车再保存起来,接下来再运行我的代码,结果lineOfTexts.length = 0(让我又郁闷了一下!)。
问题:为什么split()函数在分解空值(即text = "")时,lineOfTexts的长度会是1而不是0?
--------------------------------------------------------------------------------------
String[] lineOfTexts = text.split( "\\n" );
for( int i = 0; i < lineOfTexts.length; i++ ) {
int lineNum = i + 1;
String[] words = lineOfTexts[i].toLowerCase().split( "\\s+" );
System.out.println( words.length );
for( int j = 0; j < words.length; j++ ) {
if( words[j].endsWith( "-" ) ) {
words[j] = words[j].replaceAll( "[^a-z]", "" );
frontWord = words[j];
} else if( j == 0 && frontWord != "" ) {
words[j] = words[j].replaceAll( "[^a-z]", "" );
frontWord = frontWord.concat( words[j] );
records.addRecord( frontWord, 1, lineNum - 1 );
frontWord = "";
} else {
words[j] = words[j].replaceAll( "[^a-z]", "" );
records.addRecord( words[j], 1, lineNum ); }
} // end internal loop
} // end external loop
--------------------------------------------------------------------------------------
首先text是一个String类型变量,它的值是从一个plain text file中打开获得的(文本读入ok的,没问题的)。问题出在当我用的文本文件为空时,lineOfTexts.length = 1(我验证过的,但为什么不时0?郁闷在这里), 而当我在空文本中打入几个回车再保存起来,接下来再运行我的代码,结果lineOfTexts.length = 0(让我又郁闷了一下!)。
问题:为什么split()函数在分解空值(即text = "")时,lineOfTexts的长度会是1而不是0?
readline方法读取行的时候吧\n去掉了,所以没有,你可以try一下。
city_goal(图灵机) :我用的确实是readLine()方法在读取文件的时候,但是我text文本传过来之前,已经在每一行后面补上"\n"了,这个没问题的。
for( int j = 0; j < ( lineOfTexts[i].equals("") ? 0 : words.length ); j++ ) {...}实在改变不了length的长度,只能多用一个选择了,如果文本为空,循环的条件就指定为0,我只能想到用这样的办法避免文件为空时,length的值为1。还是要谢谢 huataixiang19810225(无名) 给我解释了为什么length为1的原因。