Question

Java // Topic 2c // Program reserves airline seats. import java.util.Scanner public class Plane {    //...

Java
// Topic 2c
// Program reserves airline seats.
import java.util.Scanner

public class Plane
{
   // checks customers in and assigns them a boarding pass
   // To the human user, Seats 1 to 2 are for First Class passengers and Seats 3 to 5 are for Economy Class passengers
   //
   public void reserveSeats()
   {
      int counter = 0;
      int section = 0;
      int choice = 0;
      String eatRest = ""; //to hold junk in input buffer
      String inName = "";
      String name = "";
      boolean goOn = true ;

      Scanner input = new Scanner( System.in );
      String[] passenger = new String[ 5 ]; // array of seats
      int firstClass = 0; // next available first class seat
      int economy = 2; // next available economy seat

while ( (goOn == true) && ( ( firstClass < 2 ) || ( economy < 5 ) ))
      {
System.out.println( "Please type 1 for First Class" );
         System.out.println( "Please type 2 for Economy" );
         System.out.println( "Please type 3 to quit");
         System.out.print( "choice: " );
         section = input.nextInt();
         eatRest = input.nextLine(); //get any end of line character remaining in the buffer to prepare for the next nextLine()
         System.out.println(" ");

         switch (section)
          {
             case 1: //user chose first class
   if ( firstClass < 2 ) //if first class available
                 {
                    System.out.print("Please enter your name: ");
                    inName = input.nextLine();
                    name = inName.trim();
                    passenger[firstClass] = name;

                    firstClass = firstClass + 1;
                    System.out.printf( "First Class. Seat #%d for %s\n", firstClass, name);
                 } // end if

               else   //first class is full
                 {
               if ( economy < 5 ) // but if economy class is available
                     {
                        System.out.println("First Class is full, Economy Class?" );
                        System.out.print( "1. Yes, 2. No. Your choice: " );
                        choice = input.nextInt();
                        eatRest = input.nextLine();

if ( choice == 1 )
                          {
                             System.out.print("Please enter your name: ");
                             inName = input.nextLine();
                             name = inName.trim();

                             passenger[economy] = name;

                             economy = economy + 1;
                             System.out.printf( "Economy Class. Seat #%d for %s\n", economy, name );
                          }
                        else
                          System.out.println( "Sorry. The next flight leaves in 3 hours." );

                      } // end if (economy < 5)
   
                  } // end else

                break;
       case 2: //user chose economy

             if ( economy < 5 )   //if economy class is available
                  {
                     System.out.print("Please enter your name: ");
                     inName = input.nextLine();
                     name = inName.trim();

                     passenger[economy] = name;

                     economy = economy + 1;
                     System.out.printf( "Economy Class. Seat #%d for %s\n", economy, name );

                  } // end if (economy < 5)

                else    //economy class is full
                  {

                     if ( firstClass < 2 ) // but if first class available
                      {
                         System.out.println("Economy Class is full, First Class?" );
                         System.out.print( "1. Yes, 2. No. Your choice: " );
                         choice = input.nextInt();
                         eatRest = input.nextLine();

                         if ( choice == 1 )
                           {
                              System.out.print("Please enter your name: ");
                              inName = input.nextLine();
                              name = inName.trim();

                              passenger[firstClass] = name;

                              firstClass = firstClass + 1;
                              System.out.printf( "First Class. Seat #%d for %s\n", firstClass, name );
                           } // end if

                         else

                           System.out.println( "Next flight leaves in 3 hours." );
                        
                       } // if (firstClass < 2)
                   } // end else
            
                break;

case 3: //user chose to quit

                System.out.println("OK");
                goOn = false;
                break;

            default:
                System.out.println("1 or 2 only. Please try again.");
                break;

         }// end switch

System.out.println();
      } // end while
     if ((firstClass > 1) && (economy > 4))

System.out.println( "The plane is now full." );

      System.out.println("Bye");
    
   } // end method reserveSeats()
} // end class Plane
-------------------------------------------------------------------------------------

1. Please translate (describe) the logic of this method back to English in detail (we are doing reverse engineering).

2. Before the system displays "Bye," we would like to display the seating chart of the flight with the human-friendly seat numbers and passenger to be in each occupied seat of this flight. Please fill in the Java code needed to complete this method. For example, It should display:

                    Seat 1     Amy Miller
                    Seat 2     Peter Pan
                     ......(Please be syntactically correct.)

3. Please do some Internet research and explain why we have to use the eatRest string in this piece of code as it is used here, in order to execute the next nextLine() method correctly and avoid bugs.

Please answer Question 1 and (either Question 2 or Question 3), clearly labeled. "Describe" or "explain" means writing more than one or two sentences. Thank you.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

(Question-1) Converting the logic of this method back to English

For each and every line of code, iam writing the explanation just above that line .

// reseveSeats() Is a method of public type which dont return anything, because its return type is void.
public void reserveSeats()
{
// Declaring and initialising a int variable 'counter' to zero.
int counter = 0;
// Declaring and initialising a int variable 'section' to zero.
int section = 0;
// Declaring and initialising a int variable 'choice' to zero.
int choice = 0;
// Declaring and initialising a String variable 'eatRest' to empty string.
String eatRest = ""; //to hold junk in input buffer
// Declaring and initialising a String variable 'inName' to empty string.
String inName = "";
// Declaring and initialising a String variable 'name' to empty string.
String name = "";
// Declaring and initialising a boolean variable 'goOn' to true.
boolean goOn = true ;

// Scanner class is used to take Input from user. It manages the input buffer.
//input object of Scanner class is instantiated here.
// To use the Scanner class, we need to import it from java.util.Scanner
Scanner input = new Scanner( System.in );

//Declaring an array of string and named it as passenger.
// this array is used to represent the passengers in respective seats.
String[] passenger = new String[ 5 ]; // array of seats

// Declaring and initialising a int variable 'firstclass' to zero.
// It is because firstclass seats are 1 and 2.
int firstClass = 0; // next available first class seat

// Declaring and initialising a int variable 'economy' to two.
// It is because economy seats are 1 and 2.
int economy = 2; // next available economy seat


//starting a while loop with condition goOn is true, and firstclass is less than two or economy is less than five.
while ( (goOn == true) && ( ( firstClass < 2 ) || ( economy < 5 ) ))

{

//System.out.println( " ") will print whatever enclosed in braces to the output console
// This line will print 'Please type 1 for First Class' to the output console.
System.out.println( "Please type 1 for First Class" );

// This line will print 'Please type 2 for Economy' to the output console.
System.out.println( "Please type 2 for Economy" );

// This line will print 'Please type 3 to quit' to the output console.
System.out.println( "Please type 3 to quit");

// This line will print 'choice: ' to the output console.
System.out.print( "choice: " );

// All the above three lines will acts as menu card for the program.

// Integer from the input buffer will be assigned to section 'variable'.
section = input.nextInt();

//String from the input buffer if any will be assigned to the string variable 'eatRest'.
eatRest = input.nextLine(); //get any end of line character remaining in the buffer to prepare for the next nextLine()

// This line will print new empty line to the output console.
System.out.println(" ");

//Using switch case for the optioned entered above which was assigned to section.
//Switch will execute the code in case which has value stored in 'section'.
switch (section)
{

//If the user input is 1, code in this case will be executed

case 1: //user chose first class

// If firstclass value is less than two.Then it will print 'please enter your name' to console.
if ( firstClass < 2 ) //if first class available
{
System.out.print("Please enter your name: ");

// Then String from the inut buffer will be assigned to inName.
inName = input.nextLine();

// inName is trimmed and assigned it to name.
// trim() will remove any spaces from front and back of the string.
name = inName.trim();
// That name will be stored in the firstclass index of the array passenger.
passenger[firstClass] = name;

// Now firstclass value should be increased with one, because firstclass index of passenger holds a value now.
// If we not increased the firstclass value, then there will be loss of data in the next turn.
firstClass = firstClass + 1;
//This line will print the 'FirstClass . seat number and the passanger name'.
System.out.printf( "First Class. Seat #%d for %s\n", firstClass, name);
} // end if

// If the firstclass value comparision in the above is not true, then this code in else will execute.
else //first class is full
{
// Since there is no availability in first class, it will prompt the user the same thing.
if ( economy < 5 ) // but if economy class is available
{
System.out.println("First Class is full, Economy Class?" );

// It asks user whether he want economy class or not, with two options '1. Yes, 2. No. Your choice: '.
System.out.print( "1. Yes, 2. No. Your choice: " );

// Integer from the input buffer will be assigned to section 'choice'.
choice = input.nextInt();
//String from the input buffer if any will be assigned to the string variable 'eatRest'.
eatRest = input.nextLine();


//Now if the choice is 1, then the code in if block executes.
if ( choice == 1 )
{
// Ask the user to enter the name.
System.out.print("Please enter your name: ");

//String from the input bufferwill be assigned to the string variable 'inName'.

inName = input.nextLine();

// inName is trimmed and assigned it to name.
// trim() will remove any spaces from front and back of the string.
name = inName.trim();

// That name will be stored in the firstclass index of the array passenger.
passenger[economy] = name;

// Now economy value should be increased with one, because economy index of passenger holds a value now.
// If we not increased the economy, then there will be loss of data in the next turn.
economy = economy + 1;

//This line will print the 'EconomyClass . seat number and the passanger name'.
System.out.printf( "Economy Class. Seat #%d for %s\n", economy, name );
}

//If the choice is not 1, then the code in else block executes.
else

//This line will prints 'Sorry. The next flight leaves in 3 hours.' to the console.
System.out.println( "Sorry. The next flight leaves in 3 hours." );

} // end if (economy < 5)

} // end else

// It will break the case.
break;

//If the user input is 2, code in this case will be executed
case 2: //user chose economy

// If economy value is less than five.Then it will print 'please enter your name' to console.
if ( economy < 5 ) //if economy class is available
{
System.out.print("Please enter your name: ");

//String from the input bufferwill be assigned to the string variable 'inName'.

inName = input.nextLine();

// inName is trimmed and assigned it to name.
// trim() will remove any spaces from front and back of the string.
name = inName.trim();

// That name will be stored in the firstclass index of the array passenger.
passenger[economy] = name;

// Now economy value should be increased with one, because economy index of passenger holds a value now.
// If we not increased the economy, then there will be loss of data in the next turn.
economy = economy + 1;

//This line will print the 'EconomyClass . seat number and the passanger name'.
System.out.printf( "Economy Class. Seat #%d for %s\n", economy, name );

} // end if (economy < 5)

// If the economy value comparision in the above is not true, then this code in else will execute.
else //economy class is full
{
// Since there is no availability in Economy class, it will prompt the user the same thing.
if ( firstClass < 2 ) // but if first class available

{

System.out.println("Economy Class is full, First Class?" );

// It asks user whether he want first class or not, with two options '1. Yes, 2. No. Your choice: '.
System.out.print( "1. Yes, 2. No. Your choice: " );

// Integer from the input buffer will be assigned to section 'choice'.
choice = input.nextInt();

//String from the input buffer if any will be assigned to the string variable 'eatRest'.
eatRest = input.nextLine();

//Now if the choice is 1, then the code in if block executes.

if ( choice == 1 )

{
// Ask the user to enter the name.
System.out.print("Please enter your name: ");

//String from the input bufferwill be assigned to the string variable 'inName'.
inName = input.nextLine();

// inName is trimmed and assigned it to name.
// trim() will remove any spaces from front and back of the string.
name = inName.trim();

// That name will be stored in the firstclass index of the array passenger.
passenger[firstClass] = name;

// Now firstclass value should be increased with one, because firstclass index of passenger holds a value now.
// If we not increased the firstclass value, then there will be loss of data in the next turn.
firstClass = firstClass + 1;

//This line will print the 'FirstClass . seat number and the passanger name'.
System.out.printf( "First Class. Seat #%d for %s\n", firstClass, name );
} // end if

//If the choice is not 1, then the code in else block executes.
else

//This line will prints 'Sorry. The next flight leaves in 3 hours.' to the console.

System.out.println( "Next flight leaves in 3 hours." );
  
} // if (firstClass < 2)
} // end else
  
// It will break the case.
break;


//If the userinput is 3, then the code in this case will execute.
case 3: //user chose to quit

// System prints ok to user.
System.out.println("OK");

//boolean value of goOn changes to false.
goOn = false;
  
// It will break the case.
break;

//If user enters other than 1 or 2 or 3. Then the code in default executes.
default:
System.out.println("1 or 2 only. Please try again.");
break;

}// end switch

System.out.println();
} // end while

//Checking if both the indexes of classes reaches maximum.

if ((firstClass > 1) && (economy > 4))

// System prints 'The plane is now full.' to user.
System.out.println( "The plane is now full." );

// System prints 'Bye' to user.
System.out.println("Bye");
  
} // end method reserveSeats()

(Question-2)Dispalying the chart.

for(int i=0; i<5; i++){

System.out.println("Seat" + (i+1) + "\t" + passenger[i]);
}

This above provided short code, if added before the "System.out.println("Bye");" line in the program will provide the required output.


(Question-3)use the eatRest string

Use of eatRest string is to take unnesessary input buffer. Which means when user asked to enter 1 or 2 or 3 for switching the cases,
If he entered more than that..then as of now there will be no problem because we are using nextInt() method to take option.
But when we use nextLine() method to take name. then the trash which is enterd by the user other than integer in the previous case
will get assigned to passenge name.. which leads to spamming the passenger name.
So soon after taking the option, ww will take the rest of the trash if any using nextLine() method and assign it to eatRest variable.
Which means eatRest variable will takes the any unrequired buffer from the input.


If you left with any doubt, feel free to ask.

Add a comment
Know the answer?
Add Answer to:
Java // Topic 2c // Program reserves airline seats. import java.util.Scanner public class Plane {    //...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Hi I need help with a java program that I need to create a Airline Reservation...

    Hi I need help with a java program that I need to create a Airline Reservation System I already finish it but it doesnt work can someone please help me I would be delighted it doesnt show the available seats when running the program and I need it to run until someone says no for booking a seat and if they want to cancel a seat it should ask the user to cancel a seat or continue booking also it...

  • Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class...

    Why does my program generate [] when viewing all guests names? ----------------------------------------------- import java.util.*; public class Delete extends Info { String name; int Id; int del; public Delete() { } public void display() { Scanner key = new Scanner(System.in); System.out.println("Input Customer Name: "); name = key.nextLine(); System.out.println("Enter ID Number: "); Id = key.nextInt(); System.out.println("Would you like to Delete? Enter 1 for yes or 2 for no. "); del = key.nextInt(); if (del == 1) { int flag = 0; //learned...

  • I have to write a C program to assign seats on each flight of the airline’s...

    I have to write a C program to assign seats on each flight of the airline’s only plane (capacity: 40 seats, in 10 rows). For the sake of simplicity, assume that each row has 4 seats labeled A, B, C, D. Your program should display the following menu of alternatives: Please type 1 for "first class" Please type 2 for "business class" Please type 3 for “economy class”. If the person types 1, then your program should assign a seat...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895...

    Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895    {        public static void header()        {            System.out.println("\tWelcome to St. Joseph's College");        }        public static void main(String[] args) {            Scanner input = new Scanner(System.in);            int d;            header();            System.out.println("Enter number of items to process");            d = input.nextInt();      ...

  • Java debugging in eclipse package edu.ilstu; import java.util.Scanner; /** * The following class has four independent...

    Java debugging in eclipse package edu.ilstu; import java.util.Scanner; /** * The following class has four independent debugging * problems. Solve one at a time, uncommenting the next * one only after the previous problem is working correctly. */ public class FindTheErrors { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); /* * Problem 1 Debugging * * This problem is to read in your first name, * last name, and current year and display them in *...

  • Must be written in java. Modularize the following code. //CIS 183 Lab 4 //Joseph Yousef import...

    Must be written in java. Modularize the following code. //CIS 183 Lab 4 //Joseph Yousef import java.util.*; public class SalaryCalc { public static void main(String [] args) { Scanner input = new Scanner(System.in); int sentinelValue = 1; //initializes sentinelValue value to 1 to be used in while loop while (sentinelValue == 1) { System.out.println("Enter 1 to enter employee, or enter 2 to end process: ");    sentinelValue = input.nextInt(); input.nextLine(); System.out.println("enter employee name: "); String employeeName = input.nextLine(); System.out.println("enter day...

  • This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static...

    This is the contents of Lab11.java import java.util.Scanner; import java.io.*; public class Lab11 { public static void main(String args[]) throws IOException { Scanner inFile = new Scanner(new File(args[0])); Scanner keyboard = new Scanner(System.in);    TwoDArray array = new TwoDArray(inFile); inFile.close(); int numRows = array.getNumRows(); int numCols = array.getNumCols(); int choice;    do { System.out.println(); System.out.println("\t1. Find the number of rows in the 2D array"); System.out.println("\t2. Find the number of columns in the 2D array"); System.out.println("\t3. Find the sum of elements...

  • import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables...

    import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables int creditScore; double loanAmount,interestRate,interestAmount; final double I_a = 5.56,I_b = 6.38,I_c = 7.12,I_d = 9.34,I_e = 12.45,I_f = 0; String instructions = "This program calculates annual interest\n"+"based on a credit score.\n\n"; String output; Scanner input = new Scanner(System.in);// for receiving input from keyboard // get input from user System.out.println(instructions ); System.out.println("Enter the loan amount: $"); loanAmount = input.nextDouble(); System.out.println("Enter the credit score: "); creditScore...

  • In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program...

    In Java Code Needed is Below the Question Using Program 3: Encapsulating Dogs, modify this program to create a database of dogs of your own. You will also include File I/O with this program. You will create 3 classes for this assignment. The first class: Create a Class representing the information that is associated with one item (one dog) of your database. Name this class Dog. Using Lab 3, this will include the information in regard to one dog. The...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT