Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following Java program that demonstrates the switch statement: impo

ID: 3586727 • Letter: C

Question

Consider the following Java program that demonstrates the switch statement:

import java.util.Scanner; // Needed for Scanner class

public class SwitchDemo {

public static void main(String[] args)

{

int number; // A number entered by the user

// Create a Scanner object for keyboard input.

Scanner keyboard = new Scanner(System.in);

// Get one of the numbers 1, 2, or 3 from the user.

System.out.print("Enter 1, 2, or 3: ");

number = keyboard.nextChar();

// Determine the number entered.

switch (number)

{

case ‘1’:

System.out.println("You entered 1.");

break;

case ‘2’:

System.out.println("You entered 2.");

break;

case ‘3’:

System.out.println("You entered 3.");

break;

default:

System.out.println("That's not 1, 2, or 3!");

}

}

}

You are required to do the following:

a) Correct the syntax error(s) in this code so that it compiles and runs.

b) Once it runs, it would always display the output as “That's not 1, 2, or 3!” even if you enter 1, 2 or 3. That means it has some semantic or logical error, which you must correct, so that the program works correctly. It should give the output as “You entered 1.” when you enter 1, “You entered 2.” when you enter 2, and “You entered 3.” when you enter 3.

For documentation, I don’t expect you to add comment in each line, but you must explain the code appropriately

Explanation / Answer

Hi,

I have fixed the issues and highlighted the code changes below.

SwitchDemo.java

import java.util.Scanner;

public class SwitchDemo {

public static void main(String[] args) {

int number;

Scanner keyboard = new Scanner(System.in);

System.out.print("Enter 1, 2 or 3: ");

number = keyboard.nextInt();

switch(number) {

case 1: System.out.println("You entered 1"); break;

case 2: System.out.println("You entered 2"); break;

case 3: System.out.println("You entered 3"); break;

default: System.out.println("That's not 1, 2 or 3");

}

}

}

Output:

Enter 1, 2 or 3: 3
You entered 3

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote