Hey guys i am having a problem with displaying a single record out of a text file the code is not reaching the "if" function in the while loop of the "getRecord" Function please help.
Everything else is working

import java.io.*;
import java.util.Scanner;
import java.util.InputMismatchException;

public class FileTest 
{
    //Globals
    public static Scanner input = new Scanner(System.in);

    public static String name = "";
    public static String address ="";
    public static int age = 0;
    public static int id =0;


  //----------------------------------------------------------------------------
    public static void main(String[] args) throws IOException {
        // TODO code application logic here

        String choice = " "; 


        System.out.println("------Sample File Program------------------------");
        System.out.println("- Press [n] Empty file and write !             -");
        System.out.println("- Press [a] add a record !                     -");
        System.out.println("- Press [s] display single record !            -");
        System.out.println("- Press [r] display file contents !            -");
        System.out.println("- Press [d] delete a record(not implemented)   -");             
        System.out.println("-------------------------------------------------");

       System.out.println("\n\n");

        choice = input.nextLine();
        choice = choice.toLowerCase();

        switch(choice.charAt(0)) 
        { 
           case 'n' :   
             System.out.println("\n-----Using New file----- ");
             getPerson();  //User input
             savePerson(); //creates file + Input saved to file
             break;

           case 'a' :  
             System.out.println("\n-----Using existing file----- "); 
             getPerson(); //user input
             appendFile(); //input appended to file 
             break;

           case 's':
             System.out.println("\n-----Display Single Record------");
             GetRecord();//THE PROBLEM
             Display();
             break;

           case 'r':
             System.out.println("\n-----Read File Contents------");
             readFile();
           break;

           default : System.out.println("Invalid input");

        }   



 }//END OF MAIN
//----------------------------------------------------------------------------



//----------------------------------------------------------------------------    
    //Gets User input
    public static void getPerson()
    {
        System.out.println("Enter Record number");
        id = Integer.parseInt(input.nextLine()); //captures new line 

        System.out.println("Enter name :");
        name = input.nextLine();

        System.out.println("Enter address :");
        address = input.nextLine();

        System.out.println("Enter age :");
        age = input.nextInt();



    }
//----------------------------------------------------------------------------  

//This method writtes data to a blank file
  public static void savePerson()
  {

      try {

            FileWriter create = new FileWriter("Data.txt"); //creates file
            BufferedWriter writefile = new BufferedWriter(create);

            writefile.write("\n"+id+" "+name+"\t"+address+ " "+ age);
            writefile.close();
            create.close();


            System.out.println("Data Saved");
        }
        catch(IOException X)
        {
            System.out.println("Error File not saved");
        }

   }

 //----------------------------------------------------------------------------

  //This method writes data to an exiting file
  public static void appendFile()
   {
      try
      {
          //file open in append mode 
          FileWriter append = new FileWriter("Data.txt",true);
          BufferedWriter writefile = new BufferedWriter(append);

          writefile.write("\n"+id+" "+name+"\t"+address+ " "+ age);

          writefile.close();
          append.close();

          System.out.println("File Written");
      }

      catch(IOException X)
      {
          System.out.println("error Append file fail!!");
      }
   }

 //----------------------------------------------------------------------------

 public static void readFile()
 { 
        //1.Create BufferReaderas object to read file
        // use while loop to read contents of file 

        try
        {
            name = "null";
            address = "None";
            age =0;
            id = 0;

            BufferedReader filein;
            filein = new BufferedReader(new FileReader("Data.txt"));

            String line = filein.readLine(); //Stores Line contents

            while(line!= null)
            {
                System.out.println(line); //prints line content to screen
                line = filein.readLine();

            }

         filein.close();

        } 
        catch(IOException X)
        {
            System.out.println("Error file not read !!");
        }

 }       
 //----------------------------------------------------------------------------    

 //DOES NOT WORK SHOULD SEARCH FILE AND GET RECORD VALUES
 public static void GetRecord() throws IOException
  {
      try 
            {
        Scanner in = new Scanner(System.in);

            //blank out fields
            name="";
            address="";
            age=0;
                    id =0;  

                        System.out.print("Enter Record Number  : ");
            int pn=Integer.parseInt(in.nextLine());


            String nameC;
            String addressC;
            int ageC =0 ;
            int idC;


              Scanner fileInp = new Scanner(new File("Data.txt")); 
              while (fileInp.hasNext())
              {
                  idC= Integer.parseInt(fileInp.nextLine());
                  nameC = fileInp.nextLine();
                  addressC=fileInp.nextLine();
                  age=fileInp.nextInt();


                    if(pn == idC)
                     {
                        id = idC;
                        name = nameC;
                        address = addressC;
                        age = ageC;
                        break;
                      }
                  fileInp.close();
              }

     }
        catch (InputMismatchException e)
        {
            System.out.println("Error, stock item could not be retrieved.");
            e.printStackTrace();
        }
  }

//---------------------------------------------------------------------------- 
  public static void Display()
    {

            System.out.println("\n"+id+name+"\t"+address+"\t"+ age);

        }

 //----------------------------------------------------------------------------




} //END OF CLASS

Recommended Answers

All 10 Replies

try and stick to the naming convention, it 'll make your code easier to read.
"it doesn't work", is a very vague description.
has it ever occured to you that maybe the record you are looking for doesn't exist?
there are quite some reasons why this might go wrong.

did you debug? did you try to read the entire contents and print it line by line? does all that do what you expect it to do?

I am not too familar with debugging but yes the file is reading and printing the content the way i intended. i am getting a "IllegalStateException: Scanner closed" error on line 202.

That's it. You close the scanner at the end of the first pass of the while loop, so the second pass fails. Better to close the scanner after you have finished with it!

Yesss its working now thanks.i need to read up more on debugging...anothe question though can a record be deleted in a sequential file using a similar algorithm in the "getRecord" method by rewritting the record chosen within the if block?

You can't just remove data from the middle of a sequential file.
Your two "easiest" options are
1. Copy the file record by record, omitting the record(s) you want to delete
or
2. Open the file as a random access file and overwrite the record with some values that your program will recognise as meaning "deleted record" when it reads the file.

Although, if your application involves updating and deleting records then maybe you should bite the bullet and use a proper database - all current versions of the JDK come with a complete JavaDB SQL database that will do all you need.

I doubt i can use a database as it was not specified by the teacher .... i have been searching the net and those are the two procedures(rewrite the file and random access file) people recomended much thanks.so i will choose 1 and will get to work

modified the program to delete and update file records now thanks for help

I have another problem this time if anyone can help with random files i am writting and displaying records from the while but i want to display all records in the file that has data say i have 100 records but only 15 contain user data i want to display only those 15 here is what i have so far. I am getting an exception on line 198.

 public static void displayFile()
    {
        int id = 0;
        int age;
        String name;
        String school;

        try
        {
            Scanner data = new Scanner(new File("Test.txt"));
            RandomAccessFile get = new RandomAccessFile("Test.txt","rw");


            while(data.hasNext()) 
            {
                //store variables from random with random instance
                 id = get.readInt();
                 age = get.readInt();
                 name= get.readUTF();
                 school = get.readUTF();

                 if(id!= 0)
                 {
                    // display data if id number is not 0
                     System.out.println("\nId # :" +id);
                     System.out.println("age :" +age);
                     System.out.println("Name :" +name);
                     System.out.println("School :" +school);

                 }

                 else if(id == 100)
                 { 
                     System.out.println("Last record");

                 }  
            }// while


        }
        catch(IOException A)
        {
            System.err.println("could not display file");
            A.printStackTrace();
        }


    }// end of method

You are reading from the "get" file while trying to control it with the Scanner's hasNext(). Because you never read from the Scanner it always hasNext - this is completely separate from what you are doing with the "get" file.

ps: Please don't leave old threads open for new questions. You should have marked this thread "solved" when you got your answer a month ago, and started a new thread for this question.

noted will do that

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.