Solved

Car Reservation Application

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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
@SBGen Method 3 36
get weblogic logged in user in java 2 57
compre toata in where clue oracle 4 55
even odd program using while loop 3 27
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

912 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

19 Experts available now in Live!

Get 1:1 Help Now