Java: An Introduction to Problem Solving and Programming (8th Edition)
Java: An Introduction to Problem Solving and Programming (8th Edition)
8th Edition
ISBN: 9780134462035
Author: Walter Savitch
Publisher: PEARSON
bartleby

Videos

Textbook Question
Book Icon
Chapter 9, Problem 1E

Write a program that allows students to schedule appointments at either 1, 2, 3, 4, 5, or 6 o’clock pm. Use an array of six strings to store the names for the time slots. Write a loop that iterates as long as the array has a free space. Within a try block, allow the user to enter a time and a name. If the time is free, put the name in the array. If the time is not free, throw a TimeInUseException. If the time is not valid, throw an InvalidTimeException. Use a catch block for each different kind of exception.

Expert Solution & Answer
Check Mark

Explanation of Solution

Creating “Main.java”:

  • Import required packages.
  • Declare the “Main” class.
    • Define the “main ()” method.
      • Create an object for the “Scanner” class.
      • Create a string array to store names.
      • Declare a variable “totalAppointments”.
      • Do the below steps till “totalAppointments” reaches 6 using “while” condition.
        • Get the name from the user.
        • Assign “false” to the Boolean variable “flag”.
        • Do until “flag” is false using “while” condition.
          • Inside “try” block,
            • Get the appointment time from the user.
            • Check whether the time is less than 1 or greater than 6.
              • Throw an exception with a message.
            • Check whether “names [appointmentTime]” is not equal to null.
              • Throw an exception with a message.
            • Assign “name” to the index “names[appointmentTime]”.
            • Assign “true” to the variable “flag”.
            • Increment the variable “totalAppointments”.
          • Catch the exception “InvalidTimeException”.
            • Print the message
          • Catch the exception “TimeInUseException”.
            • Print the message.
          • Catch the exception “Exception”.
            • Print the message.
      • Loop from 1 to 6 using “for” loop.
        • Print the makes and time for each person.

Creating “InvalidTimeException.java”:

  • Define a class “InvalidTimeException” that extends “Exception”.
    • Define a parameterized constructor.
      • Call the parent class’s method using “super ()” by passing the message.

Creating “TimeInUseException.java”:

  • Define a class “TimeInUseException” that extends “Exception”.
    • Define a parameterized constructor.
      • Call the parent class’s method using “super ()” by passing the message.

Program:

Main.java:

//Import required package

import java.util.*;

//Define the main class

public class Main

{

    //Define the main method

    public static void main(String[] args)

    {

        //Create an object for the scanner class

        Scanner sc = new Scanner(System.in);

        //Create a string array to store names

        String names[] = new String[7];

        //Declare a variable

        int totalAppointments = 0;

        //Do until the value reaches 6

        while(totalAppointments < 6)

        {

            //Get the name from the user

System.out.print("\nWhat is your name? ");

            String name = sc.next();

            //Declare a Boolean variable

            boolean flag = false;

            //Do until flag is false

            while(!flag)

            {

                //Try block

                try

                {

//Get the appointment time from the user

System.out.print("When would you like to make an appointment? ");

int appointmentTime = sc.nextInt();

//Check whether the appointment time is less than 1 or greater than 6

if(appointmentTime < 1 || appointmentTime > 6)

                        //Throw an exception

throw new InvalidTimeException("Time value not in range");

//Check if the appointment time is already fixed

if (names[appointmentTime] != null)

                        //Throw an exception

throw new TimeInUseException("appointment already made at that time");

//Save the name at the scheduled time index

names[appointmentTime] = name;

                    //Assign true

                    flag = true;

                    //Increment the variable

                    totalAppointments ++;

                }

                //Catch block

                catch (InvalidTimeException e)

                {

                    //print the message

System.out.println("Sorry, that is not a legal time");

                }

                //Catch block

                catch (TimeInUseException e)

                {

                    //print the message

System.out.println ("Sorry, that time is already in use");

                }

                //Catch block

                catch (Exception e)

                {

                    //print the message

System.out.println("Bad time format, should just be an integer");

// Use up the rest of the line

                    sc.nextLine();

                }

            }

        }

        //Print the statement

System.out.println("-----------------------------------\nScheduled Time\n\n");

        for(int i=1; i<=6; i++)

        {

//Print the names and the appointmentTime for each person

System.out.println("At " + i +"PM is " + names[i]);

        }

    }

}

InvalidTimeException.java:

//Define a class that throws Exception

public class InvalidTimeException extends Exception

{

    //Define a parameterized constructor

    public InvalidTimeException(String reason)

    {

//Call the parent class's method by passing the message

        super(reason);

    }

}

TimeInUseException.java:

//Define a class that throws Exception

public class TimeInUseException extends Exception

{

    //Define a parameterized constructor

    public TimeInUseException(String reason)

    {

//Call the parent class's method by passing the message

        super(reason);

    }

}

Sample Output

Output:

What is your name? Charles

When would you like to make an appointment? 6

What is your name? Adams

When would you like to make an appointment? 6

Sorry, that appointmentTime is already in use

When would you like to make an appointment? 5

What is your name? Bekkie

When would you like to make an appointment? 1

What is your name? David

When would you like to make an appointment? 4

What is your name? Sam

When would you like to make an appointment? 3

What is your name? Iris

When would you like to make an appointment? 2

-----------------------------------

Scheduled Time

At 1PM is Bekkie

At 2PM is Iris

At 3PM is Sam

At 4PM is David

At 5PM is Adams

At 6PM is Charles

Want to see more full solutions like this?

Subscribe now to access step-by-step solutions to millions of textbook problems written by subject matter experts!
Students have asked these similar questions
This is the question - In the exercises in Chapter 6, you created a class named Purchase. Each Purchase contains an invoice number, amount of sale, amount of sales tax, and several methods. Add get methods for the invoice number and sale amount fields so their values can be used in comparisons. Next, write a program that declares an array of five Purchase objects and prompt a user for their values. Then, in a loop that continues until a user inputs a sentinel value of Z, ask the user whether the Purchase objects should be sorted and displayed in invoice number order or sale amount order. This is the code I have. The programming isn't likeing what I have at all for the area where it says to write code -  public class Purchase {    private int invoiceNumber;    private double saleAmount;    private double tax;    private static final double RATE = 0.05;    public void setInvoiceNumber(int num)    {       invoiceNumber = num;    }    public void setSaleAmount(double amt)    {…
Write a program that creates an array to hold 5 temperature values (integers are fine).   Using a for loop, prompt the user to enter each temperature individually.  (If you don't feel like typing in the individual temperatures you can the Random object to generate random numbers between 0 and 100 and assign to each item in the for loop.) After the values are stored in the array, write another for loop that looks at each temperature and if it is 65 or higher, print "Nice day!", otherwise print "Chilly day".
Using Java enter the CountSentences class that performs this function:Instructs the user to type a number which indicates how many words / sentences will be typed (number that indicatesarray size and it should be bigger than 10 and divisible by 5).Using the for loop ask the user to fill in the string values ​​with words / sentences.Show how many words / sentences have been typed in total and using  methodShow which shows as an output the strings from the array that meet the following conditions: • Less than 15% of sentence characters are numbers,• No less than 9 vowels (case insensitive),• The sentence should contain a maximum of 12 words,• The last character of the sentence has to be a number.The methodShow method accepts an array as a parameter and returns also an array which contains all the sentences/strings of which meets the above conditions.

Chapter 9 Solutions

Java: An Introduction to Problem Solving and Programming (8th Edition)

Additional Engineering Textbook Solutions

Find more solutions based on key concepts
Knowledge Booster
Background pattern image
Computer Science
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.
Similar questions
SEE MORE QUESTIONS
Recommended textbooks for you
  • Text book image
    EBK JAVA PROGRAMMING
    Computer Science
    ISBN:9781337671385
    Author:FARRELL
    Publisher:CENGAGE LEARNING - CONSIGNMENT
Text book image
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Definition of Array; Author: Neso Academy;https://www.youtube.com/watch?v=55l-aZ7_F24;License: Standard Youtube License