0

I need to print the data out that has been inputted from the user using 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)
        {

        }
     }
}

3 Answers 3

2

You need to use ad.writeInt(emp.id) because ad.write(int) only writes a single byte.

Sign up to request clarification or add additional context in comments.

1 Comment

Such small mistakes make me mad Dx thank you so much...its all fixed now :)
2

Assuming this is the only thing

emp.id = br.read();

should be

emp.id = Integer.parseInt(br.readLine());

BufferedReader.read() reads a single character

Unless of course id is just a single character.

1 Comment

Thank youuu :D The inputs are being taken properly now...but it is still not showing the values entered.
1

Class Employee must be Serializable

 class Employee implements Serializable
 {
   int id;
   String name;
   double salary;
 }

also print exception in catch block then you can get what is wrong.

1 Comment

Ok I made it serializable but I am still getting the same problem. It takes the employee id but then asks for both the name ans salary together. I type some name and then it gives numberformatexception.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.