Results 1 to 3 of 3
Like Tree1Likes
  • 1 Post By Tolls

Thread: switch statement

  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default switch statement

    i was hopeing to be able to use a switch statement like this, but found out you can't use strings. i can't use char, since 16 is there. how else can i set this up?

    Java Code:
    // Get the length of the note
    	public static String findLengthOfNote(String noteLength) {
    		char lastNumber = noteLength.charAt(noteLength.length()-1);
    		String number = Character.toString(lastNumber);
    		switch (number) {
    			case "2": noteLength = "Half - note"; break;
    			case "4": noteLength = "Fourth - note"; break;
    			case "8": noteLength = "One-eigth note"; break;
    			case "16": noteLength = "One-sixteenth note"; break;
    			default: noteLength = "Invalid length note."; break;
    		}
    		return noteLength;
    		
    	}

  2. #2
    sehudson's Avatar
    sehudson is offline Senior Member
    Join Date
    Mar 2010
    Posts
    364
    Rep Power
    5

    Default Re: switch statement

    Java SE 7 will support Strings in switch statements, but currently cannot.

    You could cast the number String to an int:

    Java Code:
    int myInt = Integer.parseInt(number);
    Then use myInt in your switch statement.

    That or use a lot of if else statements instead of the switch statement.

  3. #3
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,224
    Rep Power
    20

    Default Re: switch statement

    Use a Map<String, String> to map from the number String to the text String you want to use.
    DarrylBurke likes this.

Similar Threads

  1. Naming a Switch Statement? Help!
    By danielinthebed in forum Advanced Java
    Replies: 1
    Last Post: 03-24-2011, 04:34 PM
  2. help with switch statement
    By java__beginner in forum New To Java
    Replies: 4
    Last Post: 03-19-2009, 03:22 PM
  3. Method in a Switch Statement
    By cart1443 in forum New To Java
    Replies: 6
    Last Post: 03-14-2008, 04:48 AM
  4. Switch Statement Help
    By bluegreen7hi in forum New To Java
    Replies: 6
    Last Post: 02-06-2008, 06:16 AM
  5. Help with gigantamous switch statement
    By trill in forum New To Java
    Replies: 2
    Last Post: 08-06-2007, 09:11 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •