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

What\'s the reasoning behind using the switch statement instead of elseif logic?

ID: 3583584 • Letter: W

Question

What's the reasoning behind using the switch statement instead of elseif logic? You are correct in using the switch statement,

import java.util.Scanner;

public class Furniture

{
public static void main(String[] args)
{
// keyboard input
Scanner kb = new Scanner(System.in);

// ask for type of wood
System.out.println("Choose the type of wood: ");
System.out.println(" 1 - pine");
System.out.println(" 2 - oak");
System.out.println(" 3 - mahogany");

int type = kb.nextInt();

// switch type of wood to price
double price;
String wood;

switch(type)
{
case 1: price = 100.0; wood = "pine"; break;
case 2: price = 225.0; wood = "oak"; break;
case 3: price = 310.0; wood = "mahogany"; break;
default: price = 0.0; wood = "unknown"; break;
}

System.out.println("$"+String.format("%.2f", price)+" for "+wood);
}
}

public class Furniture2
{
public static void main(String[] args)
{
// keyboard input
Scanner kb = new Scanner(System.in);

// ask for type of wood
System.out.println("Do you want pine(1), oak(2), or mahogany(3)? ");

int type = kb.nextInt();

// switch type of wood to price
double price;
String wood;

switch(type)
{
case 1: price = 100.0; wood = "pine"; break;
case 2: price = 225.0; wood = "oak"; break;
case 3: price = 310.0; wood = "mahogany"; break;
default: price = 0.0; wood = "unknown"; break;
}

// check for small/large table
System.out.print("Do you want a small (1) or large(2) table? ");

int table = kb.nextInt();

if(table == 2)
{
price += 35;
}


System.out.println("$"+String.format("%.2f", price)+" for "+wood);
}
}

Explanation / Answer

This Program can be done through elseif logic but that will increase the line of code and make the program a little bit complex and difficult to understand in one go.Switch is making program easy to read and understand and making it a little bit short.

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