Search Product Code in Binary File

A binary file named "ABC.DAT" contains the product code (pc), unit price (up) and quantity (q) for number of items. Write a method to accept a product code 'p' and check the availability of the product and display with an appropriate message.

The method declaration is as follows:
void findpro(int p)

import java.io.*;
import java.util.Scanner;
class ReadData{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        System.out.print("Product code to be searched: ");
        int p = Integer.parseInt(in.nextLine());
        findpro(p);
    }
    public static void findpro(int p){
        boolean eof = false;
        boolean found = false;
        try{
            FileInputStream fis = new FileInputStream("ABC.DAT");
            DataInputStream dis = new DataInputStream(fis);
            while(!eof){
                int pc = dis.readInt();
                double up = dis.readDouble();
                int q = dis.readInt();
                if(p == pc){
                    found = true;
                    break;
                }
            }
        }catch(EOFException e){
            System.out.println("Reached end of file!");
            eof = true;
        }
        catch(IOException e){
            System.out.println("Input Output Error");
        }
        if(found)
            System.out.println(p + " available!");
        else
            System.out.println(p + " unavailable.");
    }
}

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory