• Post Reply Bookmark Topic Watch Topic
  • New Topic

enum  RSS feed

 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if I have a



in my test code, I want to check if the input String is "Mark" or "Steve", how do I write it ?

I know I can do



But what if I don't want to use switch/case syntax and just want to check the input is MARK or STEVE, what's the syntax ?
 
mohammad mahdi ghaseminya
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
this is very simple example in enum:


 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
mohammad mahdi ghaseminya.

Welcome to JavaRanch.
 
mohammad mahdi ghaseminya
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks!



 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@mohammad mahdi ghaseminya

Please donot provide code here just guide the person how to do it..

This is not a place for spoon feeding,
 
Shanky Sohar
Ranch Hand
Posts: 1051
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...
 
Lalit Mehra
Ranch Hand
Posts: 384
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you do not wish to use switch then the only ways out is either using IF ELSE or "?" ternary operator

all you need will be to instantiate an enum type variable and then check it with all the possible values

 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raj Ohadi wrote:if I have a


This is not valid Java syntax to define an enum. The = and semi-colon don't belong there. An enum is like a class:


Raj Ohadi wrote:
in my test code, I want to check if the input String is "Mark" or "Steve", how do I write it ?

Besides a switch, you can just use ==:
 
Raj Ohadi
Ranch Hand
Posts: 316
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public enum Name {
MARK, JOHN, STEVE
}

public testIt(Name name) {
if(name == Name.MARK) {...} // line 1
if(name.equals(Name.MARK) {...} // line 2
}



Question:

what's the more proper way to test if an input variable "name" is quals to certain enum ? line 1 or line 2 ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
== (line 1) works fine with enums, it is not necessary to use equals().
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!