Question

Pick a switch statement from the reading. Put it into a main() Java program and make...

Pick a switch statement from the reading. Put it into a main() Java program and make it work.

  • Attach the .java file and
  • copyAndPaste the output into the WriteSubmissionBox

The switch Statement

S1.51

Multiway if-else statements can become unwieldy when you must choose from among many possible courses of action. If the choice is based on the value of an integer or character expres- sion, the switch statement can make your code easier to read.

The switch statement begins with the word switch followed by an expression in parenthe- ses. This expression is called the controlling expression. Its value must be of type int, char, byte, short, or String. The switch statement in the following example determines the price of a ticket according to the location of the seat in a theater. An integer code that indicates the seat location is the controlling expression:

int seatLocationCode; <CodehereassignsavaluetoseatLocationCode > .. .
double price = −0.01;
switch (seatLocationCode)
{

case 1: System.out.println("Balcony."); price = 15.00;
break;

case 2: System.out.println("Mezzanine."); price = 30.00;
break;

case 3: System.out.println("Orchestra."); price = 40.00;
break;

default:
System.out.println("Unknown ticket code."); break;

    } // end switch

The switch statement contains a list of cases, each consisting of the reserved word case, a constant, a colon, and a list of statements that are the actions for the case. The constant after the word case is called a case label. When the switch statement executes, the controlling expres- sion—in this example, seatLocationCode—is evaluated. The list of alternative cases is searched until a case label that matches the current value of the controlling expression is found. Then the action associated with that label is executed. You are not allowed to have duplicate case labels, as that would be ambiguous.

If no match is found, the case labeled default is executed. The default case is optional. If there is no default case, and no match is found to any of the cases, no action takes place. Although the default case is optional, we encourage you to always use it. If you think your cases cover all the possibilities without a default case, you can insert an error message or an assertion as the default case. You never know when you might have missed some obscure case.

Notice that the action for each case in the previous example ends with a break statement. If you omit the break statement, the action just continues with the statements in the next case until it reaches either a break statement or the end of the switch statement. Sometimes this feature is desirable, but sometimes omitting the break statement causes unwanted results.

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

CODE:

import java.io.*;

class Test1 {

    public static void main(String args[]) throws IOException {

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter seat code:");

        int seatLocationCode = Integer.parseInt(br.readLine());

        double price = -0.01;

        switch (seatLocationCode) {

        case 1:

            System.out.println("Balcony.");

            price = 15.00;

            break;

        case 2:

            System.out.println("Mezzanine.");

            price = 30.00;

            break;

        case 3:

            System.out.println("Orchestra.");

            price = 40.00;

            break;

        default:

            System.out.println("Unknown ticket code.");

            // break not required in default case

        }

        System.out.println("Ticket Price:" + price);

    }

}

SCREENSHOT:

OUTPUT:

Enter seat code:
1
Balcony.
Ticket Price:15.0

Enter seat code:
3
Orchestra.
Ticket Price:40.0

Please upvote if you like my answer and comment below for any queries.

Add a comment
Know the answer?
Add Answer to:
Pick a switch statement from the reading. Put it into a main() Java program and make...
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
  • How would this switch statement be modified to not use "continue"? This piece of code is...

    How would this switch statement be modified to not use "continue"? This piece of code is part of a larger assignment and that assignment prohibits the use of "continue" for switch statements. How do I modify this code so that it still does what I want it to do, without using "continue"? while (true) { choice = displayMenu(keyboard); switch (choice) { case 'D': case 'd': { courseStudents.displayStudentList();    continue; } case 'A': case 'a': { int id; double stGpa; System.out.println("Enter...

  • // Group Names: // Date: // Program Description: //   Import required packages //--> //   Declare class...

    // Group Names: // Date: // Program Description: //   Import required packages //--> //   Declare class (SwitchDoLab) //--> {    //   Declare the main method    //-->    {        //   Declare Constant integers SUM = 1, FACTORIAL = 2, QUIT = 3.        //-->        //-->        //-->        //   Create an integer variable named choice to store user's option.        //-->        //   Create a Scanner object        //   Create...

  • 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 = "";      ...

  • Eclipse Java Oxygen Question 11 pts A compile-time error occurs when Group of answer choices c....

    Eclipse Java Oxygen Question 11 pts A compile-time error occurs when Group of answer choices c. there’s a syntax error in a Java statement a. the Java compiler can’t be located b. bytecodes can’t be interpreted properly c. there’s a syntax error in a Java statement Flag this Question Question 21 pts An error that lets the application run but produces the wrong results is known as a Group of answer choices d. syntax error c. logic error a. runtime...

  • QUESTION 1 Which statement results in the value false? The value of count is 0; limit...

    QUESTION 1 Which statement results in the value false? The value of count is 0; limit is 10. (count != 0)&&(limit < 20) (count == 0)&&(limit < 20) (count != 0)||(limit < 20) (count == 0)&&(limit < 20) 10 points    QUESTION 2 If this code fragment were executed in an otherwise correct and complete program, what would the output be? int a = 3, b = 2, c = 5 if (a > b) a = 4; if (...

  • Programming Project 3 See Dropbox for due date Project Outcomes: Develop a Java program that uses:...

    Programming Project 3 See Dropbox for due date Project Outcomes: Develop a Java program that uses: Exception handling File Processing(text) Regular Expressions Prep Readings: Absolute Java, chapters 1 - 9 and Regular Expression in Java Project Overview: Create a Java program that allows a user to pick a cell phone and cell phone package and shows the cost. Inthis program the design is left up to the programmer however good object oriented design is required.    Project Requirements Develop a text...

  • Java Questions When creating a for loop, which statement will correctly initialize more than one variable?...

    Java Questions When creating a for loop, which statement will correctly initialize more than one variable? a. for a=1, b=2 c. for(a=1, b=2) b. for(a=1; b=2) d. for(a = 1&& b = 2) A method employee() is returning a double value. Which of the following is the correct way of defining this method? public double employee()                                    c. public int employee() public double employee(int t)                  d. public void employee() The ____ statement is useful when you need to test a...

  • In the processLineOfData, write the code to handle case "H" of the switch statement such that:...

    In the processLineOfData, write the code to handle case "H" of the switch statement such that: An HourlyEmployee object is created using the firstName, lastName, rate, and hours local variables. Notice that rate and hours need to be converted from String to double. You may use parseDouble method of the Double class as follows:               Double.parseDouble(rate) Call the parsePaychecks method in this class passing the HourlyEmployee object created in the previous step and the checks variable. Call the findDepartment method...

  • QUESTION 7 Which of the following is a valid C++ assignment statement? (assume each letter is...

    QUESTION 7 Which of the following is a valid C++ assignment statement? (assume each letter is a different variable) A.y=b-c B.y +z = x C.x = a bi D.x = -(y*z): Ex = (x + (y z): QUESTION 8 Which of the following is a valid variable name according to C++ naming rules? A 2ndName B.%Last_Name C@Month D#55 Eyear03 QUESTION 9 Which library must be included to enable keyboard input? A kbdin B. cstdlib C input Diostream E lomanip QUESTION...

  • Adv. Java program - create a math quiz

    Create a basic math quiz program that creates a set of 10 randomly generated math questions for the following operations:AdditionSubtractionMultiplicationDivisionModuloExponentThe following source files are already complete and CANNOT be changed:MathQuiz.java (contains the main() method)OperationType.java (defines an enumeration for valid math operations and related functionality)The following source files are incomplete and need to be coded to meet the indicated requirements:MathQuestionable.javaA Random object called RANDOM has already been declared and assigned, and you must not change this assignment in any way.Declare and assign an interface integer called MAX_SMALL and assign it 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