1

If i get the user to input a value in String from the menu output on the screen. How can i use that input for a switch statement? it keeps it can be only used for int. For example, if a user enters a, i want it to switch to the case statement and do the actions. Sorry if this is confusing.

public static void sortData(short days[], String name[]) {
    String choice;
    Scanner kd = new Scanner(System.in);

    System.out.println("a. Sort by Name\nb. Sort by Day");
    choice = kd.next();                       // ????????

    switch (choice) {
    case 1: {                                // ?????????
  • Can't you just get the first character of the string and use that instead of a String? As far as I know you _can_ use chars for a switch. – 11684 Apr 14 '13 at 16:22
  • @11684 i tried using char, it would compile without any errors but when i entered input, it woudnt display anything. hence i changed it to String. – user2278109 Apr 14 '13 at 16:25
  • Are you using Java 7 ? You can use String in cases then ! – AllTooSir Apr 14 '13 at 16:26

2 Answers2

3

You could define a list of strings for your accepted choices and use indexOf to find the entered input. After that you can use the index in your switch.

Like this

List<String> options = Arrays.asList("name", "day", "color", "smell");
switch (options.indexOf(choice)) {
case 0: // name
    ...
case 1: // day
    ...
... // etc
default: // none of them
}

However, using the numbers is not very readable.

Another idea: define an enum and use valueOf(choice). In this case you have to catch an IllegalArgumentException for non matching inputs.

enum Options {
    name, day, color, smell
}

and then

try {
    switch (Options.valueOf(choice)) {
    case name: ...
    case day: ...
    // etc
    }
} catch (IllegalArgumentException ex) {
    // none of them
}

or, finally, you switch to Java 7 ;-)

likeitlikeit
  • 5,563
  • 5
  • 42
  • 56
obecker
  • 2,132
  • 1
  • 19
  • 23
0

As far as I know, this is okay:

public static void sortData(short days[], String name[]) {
    char choice;
    Scanner kd = new Scanner(System.in);

    System.out.println("a. Sort by Name\nb. Sort by Day");
    choice = kd.next().toCharArray()[0];

    switch (choice) {
    case 'a':
        // do something
        break;
    case 'b';
        // do something else
        break;
    }
}

Not tested

11684
  • 7,356
  • 12
  • 48
  • 71