Solved

Car Reservation Application

Posted on 2011-09-30
4
812 Views
Last Modified: 2012-05-12
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.*;

public class CarReservation extends JFrame
{
   // JLabel and JSpinner to display date
   private JLabel selectDateJLabel;
   private JSpinner dateJSpinner;

   // JLabel and JTextField to display name
   private JLabel nameJLabel;
   private JTextField nameJTextField;

   // JButton to reserve car
   private JButton reserveCarJButton;

   // BufferedReader and PrintWriter to allow 
   // reading from, and writing to, a file 
   private BufferedReader input; 
   private PrintWriter output; 
   
   // no-argument constructor
   public CarReservation()
   {
      createUserInterface();
   }

   // create and position GUI components
   public void createUserInterface()
   {
      // get content pane for attaching GUI components
      Container contentPane = getContentPane();
      
      // enable explicit positioning of GUI components
      contentPane.setLayout( null );
      
      // set up selectDateJLabel
      selectDateJLabel = new JLabel();
      selectDateJLabel.setBounds( 16, 16, 96, 23 );
      selectDateJLabel.setText( "Select the date:" );
      contentPane.add( selectDateJLabel );

      // set up dateJSpinner
      dateJSpinner = new JSpinner( new SpinnerDateModel() );
      dateJSpinner.setBounds( 16, 43, 250, 23 );
      dateJSpinner.setEditor( new JSpinner.DateEditor( 
         dateJSpinner, "MM/dd/yyyy" ) ); 
      contentPane.add( dateJSpinner );
      dateJSpinner.addChangeListener(
      
         new ChangeListener() // anonymous inner class
         {
            // event handler called when dateJSpinner is changed
            public void stateChanged( ChangeEvent event )
            {
               dateJSpinnerChanged( event );
            }
            
         } // end anonymous inner class
         
      ); // end call to addActionListener            
            
      // set up nameJLabel
      nameJLabel = new JLabel();
      nameJLabel.setBounds( 16, 70, 100, 23 );
      nameJLabel.setText( "Name: " );
      contentPane.add( nameJLabel );
            
      // set up nameJTextField
      nameJTextField = new JTextField();
      nameJTextField.setBounds( 16, 97, 250, 23 );
      contentPane.add( nameJTextField );
      
      // set up reserveCarJButton
      reserveCarJButton = new JButton();
      reserveCarJButton.setBounds( 16, 130, 250, 23 );
      reserveCarJButton.setText( "Reserve Car" );
      contentPane.add( reserveCarJButton );
      reserveCarJButton.addActionListener(

         new ActionListener() // anonymous inner class
         {
            // event handler called when reserveCarJButton is clicked
            public void actionPerformed( ActionEvent event )
            {
               reserveCarJButtonActionPerformed( event );
            }

         } // end anonymous inner class

      ); // end call to addActionListener
            
      // set properties of application's window
      setTitle( "Car Reservation" ); // set title bar string
      setSize( 287, 190 );           // set window size
      setVisible( true );            // display window

   } // end method createUserInterface
   
   // write reservation to a file
   private void reserveCarJButtonActionPerformed( ActionEvent event )
   {
	  File reserveFile = new File( "reservations.txt" ); 
	  
	  // read reservations from, and write a reservation to, a file
	  try
	  {
		  // create buffered read to open and read text file
		  FileReader inputFile = new FileReader ( reserveFile );
		  input = new BufferedReader( inputFile ); 
		  
		  // get selected date
		  Date fullDate = ( Date ) dateJSpinner.getValue();
		  String currentDate = fullDate.toString();
		  String monthDay = currentDate.substring( 0, 10 );
		  String year = currentDate.substring( 24, 28 ); 
		  currentDate = monthDay + " " + year; 
		  
		  int dateCount = 1;
		  String contents = input.readLine(); 
		  
		  // check if too many cars are reserved
		  while ( contents != null ) 
		  { 
			  // check reservation date
			  if ( contents.equals( currentDate ) ) 
			  { 
				  //check reservation number
				  if ( dateCount < 4 ) 
				  {
					  dateCount++; 
				  }
				  else
				  {
					  JOptionPane.showMessageDialog( this, "Too many " + 
						  "cars have already been reserved for that day.",
						  "Sorry", JOptionPane.INFORMATION_MESSAGE );
			
					  // disable reserveCarJbutton
					  reserveCarJButton.setEnabled( false );
				  
					  return; // exit method 
				  }
			  
			  } // end if
		  
			  contents = input.readLine(); // read next line
		  
		  } // end while 
	  
		  input.close(); // close BufferedReader 
	  
		  // creat PrintWriter to open and write text file 
		  FileWriter outputFile = new FileWriter( reserveFile, true );
		  output = new PrintWriter( outputFile ); 
	  
		  // write user input to file 
		  output.println( currentDate );
		  output.println( nameJTextField.getText() ); 
	  
		  JOptionPane.showMessageDialog( this, 
			  "Your car has been reserved.", "Thank you", 
			  JOptionPane.INFORMATION_MESSAGE );
		  
		  output.close(); // close PrintWriter
	  
	  } // end try 
	  catch ( IOException exception ) 
	  {
		  JOptionPane.showMessageDialog( this, "Invalid file.",
			  "Error", JOptionPane.ERROR_MESSAGE ); 
			  
		  // disable dateJSpinner and reserveCarJButton
		  dateJSpinner.setEnabled( false );
		  reserveCarJButton.setEnabled( false ); 
	  }
	  
	  nameJTextField.setText( "" );
						 
   } // end method reserveCarJButtonActionPerformed

   // enable reserveCarJButton
   private void dateJSpinnerChanged( ChangeEvent event )
   {
      reserveCarJButton.setEnabled( true );
   
   } // end method dateJSpinnerChanged
   
   // main method
   public static void main( String[] args )
   {
      CarReservation application = new CarReservation();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

   } // end method main

} // end class CarReservation

Open in new window


stuck on this programming, not sure what im missing and i also have no error when i run the command prompt. however, when i the run the application, i get error invalid file, i should of got that say Your car has been reserved. Image im talking about
   error running
0
Comment
Question by:bakerule22
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
4 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36894132
This is because you iopen FileWriter with secind parameterrt true which implies thta there is a file - if it not found - then it says invalid file
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36894173
No, actulaly this can open anly existing file:

        FileReader inputFile = new FileReader ( reserveFile );

see:
http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html#FileReader%28java.io.File%29


that's were it thows execption
0
 
LVL 47

Accepted Solution

by:
for_yan earned 125 total points
ID: 36894202
This works and saus youyr car has been reservered as expected

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.*;

public class CarReservation extends JFrame
{
   // JLabel and JSpinner to display date
   private JLabel selectDateJLabel;
   private JSpinner dateJSpinner;

   // JLabel and JTextField to display name
   private JLabel nameJLabel;
   private JTextField nameJTextField;

   // JButton to reserve car
   private JButton reserveCarJButton;

   // BufferedReader and PrintWriter to allow
   // reading from, and writing to, a file
   private BufferedReader input;
   private PrintWriter output;

   // no-argument constructor
   public CarReservation()
   {
      createUserInterface();
   }

   // create and position GUI components
   public void createUserInterface()
   {
      // get content pane for attaching GUI components
      Container contentPane = getContentPane();

      // enable explicit positioning of GUI components
      contentPane.setLayout( null );

      // set up selectDateJLabel
      selectDateJLabel = new JLabel();
      selectDateJLabel.setBounds( 16, 16, 96, 23 );
      selectDateJLabel.setText( "Select the date:" );
      contentPane.add( selectDateJLabel );

      // set up dateJSpinner
      dateJSpinner = new JSpinner( new SpinnerDateModel() );
      dateJSpinner.setBounds( 16, 43, 250, 23 );
      dateJSpinner.setEditor( new JSpinner.DateEditor(
         dateJSpinner, "MM/dd/yyyy" ) );
      contentPane.add( dateJSpinner );
      dateJSpinner.addChangeListener(

         new ChangeListener() // anonymous inner class
         {
            // event handler called when dateJSpinner is changed
            public void stateChanged( ChangeEvent event )
            {
               dateJSpinnerChanged( event );
            }

         } // end anonymous inner class

      ); // end call to addActionListener

      // set up nameJLabel
      nameJLabel = new JLabel();
      nameJLabel.setBounds( 16, 70, 100, 23 );
      nameJLabel.setText( "Name: " );
      contentPane.add( nameJLabel );

      // set up nameJTextField
      nameJTextField = new JTextField();
      nameJTextField.setBounds( 16, 97, 250, 23 );
      contentPane.add( nameJTextField );

      // set up reserveCarJButton
      reserveCarJButton = new JButton();
      reserveCarJButton.setBounds( 16, 130, 250, 23 );
      reserveCarJButton.setText( "Reserve Car" );
      contentPane.add( reserveCarJButton );
      reserveCarJButton.addActionListener(

         new ActionListener() // anonymous inner class
         {
            // event handler called when reserveCarJButton is clicked
            public void actionPerformed( ActionEvent event )
            {
               reserveCarJButtonActionPerformed( event );
            }

         } // end anonymous inner class

      ); // end call to addActionListener

      // set properties of application's window
      setTitle( "Car Reservation" ); // set title bar string
      setSize( 287, 190 );           // set window size
      setVisible( true );            // display window

   } // end method createUserInterface

   // write reservation to a file
   private void reserveCarJButtonActionPerformed( ActionEvent event )
   {
	  File reserveFile = new File( "reservations.txt" );

	  // read reservations from, and write a reservation to, a file
         String currentDate = null;
	  try
	  {
		  // create buffered read to open and read text file
          if(reserveFile.exists()){
		  FileReader inputFile = new FileReader ( reserveFile );
		  input = new BufferedReader( inputFile );

		  // get selected date
		  Date fullDate = ( Date ) dateJSpinner.getValue();
		  currentDate = fullDate.toString();
		  String monthDay = currentDate.substring( 0, 10 );
		  String year = currentDate.substring( 24, 28 );
		  currentDate = monthDay + " " + year;

		  int dateCount = 1;
		  String contents = input.readLine();

          System.out.println("rached here");

		  // check if too many cars are reserved
		  while ( contents != null )
		  {
			  // check reservation date
			  if ( contents.equals( currentDate ) )
			  {
				  //check reservation number
				  if ( dateCount < 4 )
				  {
					  dateCount++;
				  }
				  else
				  {
					  JOptionPane.showMessageDialog( this, "Too many " +
						  "cars have already been reserved for that day.",
						  "Sorry", JOptionPane.INFORMATION_MESSAGE );

					  // disable reserveCarJbutton
					  reserveCarJButton.setEnabled( false );

					  return; // exit method
				  }

			  } // end if

                 System.out.println("rached here 2");
			  contents = input.readLine(); // read next line

                System.out.println("rached here 3");

		  } // end while

		  input.close(); // close BufferedReader
          }

            System.out.println("rached here 4");

		  // creat PrintWriter to open and write text file

            FileWriter outputFile = null;
          if(reserveFile.exists())
		   outputFile = new FileWriter( reserveFile, true );
             else   outputFile = new FileWriter( reserveFile, false );
		  output = new PrintWriter( outputFile );

		  // write user input to file
		  output.println( currentDate );
		  output.println( nameJTextField.getText() );

		  JOptionPane.showMessageDialog( this,
			  "Your car has been reserved.", "Thank you",
			  JOptionPane.INFORMATION_MESSAGE );

		  output.close(); // close PrintWriter
	  
	  } // end try
	  catch ( IOException exception )
	  {
          exception.printStackTrace();
		  JOptionPane.showMessageDialog( this, "Invalid file.",
			  "Error", JOptionPane.ERROR_MESSAGE );

		  // disable dateJSpinner and reserveCarJButton
		  dateJSpinner.setEnabled( false );
		  reserveCarJButton.setEnabled( false );
	  }

	  nameJTextField.setText( "" );

   } // end method reserveCarJButtonActionPerformed

   // enable reserveCarJButton
   private void dateJSpinnerChanged( ChangeEvent event )
   {
      reserveCarJButton.setEnabled( true );

   } // end method dateJSpinnerChanged

   // main method
   public static void main( String[] args )
   {
      CarReservation application = new CarReservation();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

   } // end method main

} // end class CarReservation

Open in new window

0
 

Author Comment

by:bakerule22
ID: 36894478
Thanks i got it working
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question