请高手指教!一个关于字符数组的问题!

bybella 2004-12-16 06:15:55
我写了一个程序
目的是将文件text.txt的每行,根据方法readRecord( String type )中的type指定是否为string类型,组成字符串。每行返回的字符串组成字符数组。文件的行数就是字符数组的长度。
文件如下:
1,2,3
1,2,3
1,2,3
假设方法调用为:String type = new String(1,2);
a = readRecord( type );
要求返回的为:a[0]=‘1’,‘2’,3
a[1]=‘1’,‘2’,3
a[2]= ‘1’,‘2’,3
现在就是方法返回的数组里面取不到值,为null。不知道是不是这种返回数组的方法有问题。请高手指点!!
程序如下:
import java.io.*;
import java.util.*;
import java.util.StringTokenizer;

public class getSqlData
{
private String currentRecord = null;
private BufferedReader file;
private String path;
private StringTokenizer token;
static String nn = new String();

//创建文件对象

public getSqlData(String filePath) throws FileNotFoundException
{
path = filePath;
file = new BufferedReader(new FileReader(path));
}
//type是一个字符串,比如"1,2,3",就表示每行中的1,2,3个元素是string类型的,所以读出来的值要加"'"单引号
//返回的是一个字符数组,将每行组成的字符串都作为数组的每个元素
public String[] readRecord( String type )
{
int maxlength = 200;
String sep1 = ",";
String sep2 = "'";
String strings[] = new String[maxlength];

try
{
while ( (currentRecord = file.readLine()) != null )
{
int n = 0;
int i = 0;
String f = "";
StringTokenizer st = new StringTokenizer( currentRecord , ",");
while (st.hasMoreTokens())
{
n ++;
nn = Integer.toString(n);
if ( type.indexOf ( nn ) == -1 )
{
f += "," + st.nextToken();
}
else f += sep1 + sep2 + st.nextToken() + sep2;
}
strings[i] = f;

i ++;
}
return strings;
}
catch ( IOException d)
{
System.out.println("error!");
return strings;
}


}

public static void main(String args[])
{
String s = "d:/text.txt";
String v = "1,2";

try{
getSqlData test= new getSqlData(s);

System.out.println((test.readRecord(v))[1]);
}catch (FileNotFoundException e)
{
System.out.println("file not found!");
}



System.out.println("success");
}
}
...全文
133 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
javacaim 2004-12-16
  • 打赏
  • 举报
回复
刚才看了一下,是你的代码有问题:
int i = 0;不应该放在循环中,应该在循环外。否则你返回的数组只有[0]有值,后面都是空!
////////////////////////////////////////////////////////////////
while ( (currentRecord = file.readLine()) != null )
{
int n = 0;
int i = 0;//这里错了!!!!
String f = "";
StringTokenizer st = new StringTokenizer( currentRecord , ",");
while (st.hasMoreTokens())
{
n ++;
nn = Integer.toString(n);
if ( type.indexOf ( nn ) == -1 )
{
f += "," + st.nextToken();
}
else f += sep1 + sep2 + st.nextToken() + sep2;
}
strings[i] = f;

i ++;
}
fireflyqt 2004-12-16
  • 打赏
  • 举报
回复
字符串数组作为方法的返回值?
是这个意思吗?
String[] func(int size) {
return new String[size];
}
bybella 2004-12-16
  • 打赏
  • 举报
回复
简单一点就是说:怎么用字符串数组作为方法的返回值?有没有例子可以借鉴一下?
wzlbaby 2004-12-16
  • 打赏
  • 举报
回复
偶现在还没你学的多呢,只能给你精神上的鼓励了,呵呵!
treeroot 2004-12-16
  • 打赏
  • 举报
回复
太长了
bybella 2004-12-16
  • 打赏
  • 举报
回复
呜呜~~~
怎么没有人回答我的问题呀?
asdmonster 2004-12-16
  • 打赏
  • 举报
回复
mark一下,呆会儿看看

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧