User created switch option?

108 views Asked by At

Is it possible to write a user-created switch case option? For example, if I had:

 String name = JOptionPane.showInputDialog(null, "Please enter your name."
 switch (name) {
     case "Adam":
         JOptionPane.showMessageDialog(null, "Your name is Adam";
     case "Julie":
         JOptionPane.showMessageDialog(null, "Your name is Julie";

I want to write a program where, when the program prompts the user for a name, if the name is not one of the cases listed, the program will create a new case for it with the exact same executed code for each case. Is this possible?

2

There are 2 answers

1
Mapsy On

No, but you wouldn't want to do it like this either. There are so many names in the world! I hear someone in Australia actually tried to name their kid 'Batman'. Do you really want to update your software for these guys?

You can skip the branching switch statement and just embed the name data programmatically.

public static final String getHelloString(final String pUserName) {
    return "Hello "+pUserName+"!";
}
0
River On

If you want to output "Your name is name", then that's fairly easy to accomplish.

Simply do

String name = JOptionPane.showInputDialog(null, "Please enter your name.");
JOptionPane.showMessageDialog(null, "Your name is " + name);

If you want to keep the switch, then do as @stvcisco suggested (in his comment) and make a default case:

String name = JOptionPane.showInputDialog(null, "Please enter your name.");
switch (name) {
 case "Adam":
     JOptionPane.showMessageDialog(null, "Your name is Adam");
     break;
 case "Julie":
     JOptionPane.showMessageDialog(null, "Your name is Julie");
     break;
 default:
     JOptionPane.showMessageDialog(null, "Your name is " + name);
     break; //This break is technically optional, but always a good idea anyways
}

The benefits of this option is it gives you the flexibility to have unique outputs for names you recognize along with a standard response for names you do not recognize.