Solved

Car Reservation Application

Posted on 2011-09-30
4
804 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
  • 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

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
count7 challenge 12 69
powerN  challenge 3 47
countAbc challenge 9 49
Core Java. What output will be and why ? 6 58
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

708 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now