• Post Reply Bookmark Topic Watch Topic
  • New Topic

Switch  RSS feed

 
Rubbal Bhusri
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method that returns a String. and On the basis of that returned String I have to choose a value from a set of different values. I tried to use the switch, but it works with only int-type of values.
Description:
I have a method that returns String branch
e.g.


Now, there are different Fees structures for different branches
e.g. CSE-500
ECE-600
ME- 800
IT-550

Now based on the branch Name returned, I have to make a logic that chooses corresponding Fees structure, I tried to pass String in Switch as e.g


Suggest me some alternative to select values based on the String returned.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For that approach to work you need to put the string values in quotes. With your code as it is, the compiler will be looking for variables CSE, ECE and ME, and won't find them.

The other thing you need to do is make sure you're using Java 7. Using strings in a switch statement was only introduced then.

But I'd actually use a different approach entirely. You aren't doing anything different in each branch, you're just selecting a particular value. So I'd suggest using a Map<String, Integer> to contain the mapping. Then it's just a simple lookup.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:I'd suggest using a Map<String, Integer> to contain the mapping. Then it's just a simple lookup.

@Rubbai: And if your branches are:
  • (a) constant
  • (b) unlikely to change
  • (c) not too numerous
  • an alternative might be to use an enum.

    Winston
     
    Rubbal Bhusri
    Ranch Hand
    Posts: 71
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Matthew Brown wrote: So I'd suggest using a Map<String, Integer> to contain the mapping. Then it's just a simple lookup.


    Can you please give me a start-up on Map<> (mapping) ?
    Because I know nothing about mapping.
     
    Bear Bibeault
    Author and ninkuma
    Marshal
    Posts: 66306
    152
    IntelliJ IDE Java jQuery Mac Mac OS X
     
    milan chovatiya
    Greenhorn
    Posts: 24
    Java Oracle Python
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    enum can be easily used in this code.....
     
    Consider Paul's rocket mass heater.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!