我用数组填充JList,但我的主要问题是应该包含字符的变量总是空的; readChar()没有得到任何东西,至少这就是我所假设的。
我正在从直接文件中读取数据库,除了从每个寄存器读取的前两个数据外,内容并不重要:1个int和25个字符。
如果某些内容被错误地读出来,我会通过查看一个充满难以辨认的字符的显示来注意到......
public static void WritingInJList (JList x) throws IOException
{
try{
RandomAccessFile file = new RandomAccessFile("database.dat","rw");
long registerSize = 78;
long numberRegisters = file.length()/registerSize;
int num=0;
String description="";
String productlist[] = new String[(int) numberRegisters];
for (int i=0;i<numberRegisters;i++)
{
file.seek(registerSize*i);
num = file.readInt(); /* int is read correctly */
for (int j=0; j<25; j++)
{description =""+file.readChar();}
productList[i] = num+"..."+description; /*variable description is blank!*/
System.out.println(productList[i]);
}
x.setListData(productList);
}catch (FileNotFoundException e){System.out.println("File Not Found");}
}
运行:
1 ...
2 ...
3 ...
4 ...
5 ...
6 ...
7 ...
8 ...
9 ...
10 ...
11 ...
12 ...
13 ...
当我使用System.out.print();跟踪问题时,如果从循环内部打印,则显示所有字符。这是代码和输出:
public static void WritingInJList (JList x) throws IOException
{
try{
RandomAccessFile file = new RandomAccessFile("database.dat","rw");
long registerSize = 78;
long numberRegisters = file.length()/registerSize;
int num=0;
String description="";
String productlist[] = new String[(int) numberRegisters];
for (int i=0;i<numberRegisters;i++)
{
file.seek(registerSize*i);
num = file.readInt();
System.out.print(num+"...");
for (int j=0; j<25; j++)
{System.out.print(""+file.readChar());} /*All chars are read perfectly*/
System.out.println("");
productList[i] = description;
}
x.setListData(productList);
}catch (FileNotFoundException e){System.out.println("File Not Found");}
}
运行:
1 ...产品1
2 ...产品2
3 ...产品3
4 ... product4的
5 ...产品5
6 ...产品6
7 ...产品7
8 ... product8
9 ... product9
10 ... product10
11 ... product11
12 ... product12
13 ... product13
我做错了什么?为什么变量 description 不显示任何内容
答案 0 :(得分:0)
你有:
for (int j=0; j<25; j++)
{description =""+file.readChar();}
每次循环都会将description
重置为单个字符。实际上,这最终会使description
仅等于最终字符。
你可能意味着更多的内容:
description="";
for (int j=0; j<25; j++)
{description =description+file.readChar();}