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
Just wanted to know, if you had a scene graph, how do you get multiple components from a specific scene node within a scene graph? Like if I wanted to get a component from wheel from the scene graph, does that require traversing still?   Like if a physics component requires a transform component and these two component are part of the same scene node. How does the physics component knows how to get the scene object's transform it is attached to, this being in a scene graph?
How to develop a C program that receives the message sent by the provided program and displays the name and email included in the message on the screen?Here is the code of the program that sends the message for reference: typedef struct {    long tipo;    struct {        char nome[50];        char email[40];    } dados;} MsgStruct; int main() {    int msg_id, status;    msg_id = msgget(1000, 0600 | IPC_CREAT);    exit_on_error(msg_id, "Creation/Connection");    MsgStruct msg;    msg.tipo = 5;    strcpy(msg.dados.nome, "Pedro Silva");    strcpy(msg.dados.email, "pedro@sapo.pt");    status = msgsnd(msg_id, &msg, sizeof(msg.dados), 0);    exit_on_error(status, "Send");    printf("Message sent!\n");}
9. Let L₁=L(ab*aa), L₂=L(a*bba*). Find a regular expression for (L₁ UL2)*L2. 10. Show that the language is not regular. L= {a":n≥1} 11. Show a derivation tree for the string aabbbb with the grammar S→ABλ, A→aB, B→Sb. Give a verbal description of the language generated by this grammar.

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
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage
Definition of Array; Author: Neso Academy;https://www.youtube.com/watch?v=55l-aZ7_F24;License: Standard Youtube License