帮我看看这个简单的问题..!

edisonlzk 2007-06-20 02:29:56
import java.io.*;

public class temp
{
public static void main(String [] args)
{
try
{
String head = "Name,ID,DS,DB";
byte[] c = new byte[40];
c = head.getBytes();
System.out.println(new String(c));
String record = "\n";

BufferedWriter fo = new BufferedWriter(new FileWriter("c:\\student.txt",true));
String[] info = new String[4];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < info.length; i++)
{
info[i] = reader.readLine();
record += info[i];
}
System.out.println(record);
fo.write(record);
fo.close();
}
catch (FileNotFoundException fe)
{
System.out.println("File Not Found");
}
catch (IOException ie)
{
System.out.println("IO Exception");
}
}
}



我想让程序实现输出字符保存到文本文件里
其格式为
Name,ID,DS,DB
a 001 90 90
b 002 90 96

当我输入两组数据以后,程序执行结果与预期结果不同,我搞了半天也没搞懂为什么,

a 001 90 90b 002 99 99null
nullnullnullnull


上面为程序执行,为什么会是这种结果
...全文
238 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
edisonlzk 2007-06-20
  • 打赏
  • 举报
回复
楼上的方法也有问题啊,
如果执行两次程序,你们想想会有什么结果呢,!
还有我应该怎么解决空值问题
beibeiG 2007-06-20
  • 打赏
  • 举报
回复
修改如下:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

// 注意类名要大写
public class Temp
{
public static void main(String [] args)
{
try
{
String head = "Name,ID,DS,DB";
byte[] c = new byte[40];
c = head.getBytes();
System.out.println(new String(c));
String record = "";

// 判断文件是否存在
File dir = new File("c:\\student.txt");
if(dir.exists())
{
// 是否有内容
FileInputStream infile = new FileInputStream(dir);
if(infile.read() < 0)
{
record = "Name ID DS DB" + "\r\n";
}
infile.close();
}

BufferedWriter fo = new BufferedWriter(new FileWriter("c:\\student.txt",true));
String[] info = new String[4];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
for (int i = 0; i < info.length; i++)
{
info[i] = reader.readLine();
record += info[i] + "\t\n";
}
System.out.println(record);

fo.write(record);

// 换行
fo.write("\r\n");
fo.close();
}
catch (FileNotFoundException fe)
{
System.out.println("File Not Found");
}
catch (IOException ie)
{
System.out.println("IO Exception");
}
}

}


搞不懂你那一堆null是怎么出来的?敲个回车也该是个空呀
foreveriong 2007-06-20
  • 打赏
  • 举报
回复
恭喜
hengxxh 2007-06-20
  • 打赏
  • 举报
回复
楼上正解!呵呵!
fool_leave 2007-06-20
  • 打赏
  • 举报
回复
不是这种结果就出轨了

reader.readLine();返回的字符串本身不含有"\r\n"
所以你看到的数据都连起来了

你输入的是两行数据,所以info[2],info[3]都是null,print后就是“null”

62,612

社区成员

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

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