我需要使用datainputstream将用户输入的数据打印出来
and dataoutputstream but this is not even taking the inputs properly.Can anyone tell me what is wrong with my code?import java.io.*;
class Employee
{
int id;
String name;
double salary;
}
public class Ch8Ex2
{
public static void main (String[] args)
{
Employee emp = new Employee();
try
{
File f1 = new File("emp1.dat");
f1.createNewFile();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
DataInputStream da = new DataInputStream(new FileInputStream(f1));
DataOutputStream ad = new DataOutputStream(new FileOutputStream(f1));
System.out.println("Enter your ID:");
emp.id = br.read();
System.out.println("Enter your name:");
emp.name = br.readLine();
System.out.println("Enter your salary:");
String str = br.readLine();
emp.salary = Double.parseDouble(str);
ad.write(emp.id);
ad.writeUTF(emp.name);
ad.writeDouble(emp.salary);
ad.flush();
ad.close();
System.out.println("ID:"+da.readInt());
System.out.println("Name:"+da.readUTF());
System.out.println("Salary:"+da.readDouble());
da.close();
}
catch(IOException e)
{
}
catch(NumberFormatException e)
{
}
}
}发布于 2013-01-01 20:35:02
您需要使用ad.writeInt(emp.id),因为ad.write(int)只写入一个字节。
发布于 2013-01-01 20:26:36
假设这是唯一一件
emp.id = br.read();应该是
emp.id = Integer.parseInt(br.readLine());BufferedReader.read() reads a single character
当然,除非id只是一个字符。
发布于 2013-01-01 20:11:58
类Employee必须是可序列化的
class Employee implements Serializable
{
int id;
String name;
double salary;
}还可以在catch块中打印异常,这样就可以知道哪里出了问题。
https://stackoverflow.com/questions/14110255
复制相似问题