Reputation: 169
I want my program to show an error message if I inputted wrong value in type and value.
The error message works well on type but it does not work on the value. What's wrong with it?
Map<String, String> Heart = new HashMap();
Heart.put("A", "Heart");
Heart.put("J", "Heart");
Heart.put("Q", "Heart");
Heart.put("K", "Heart");
Heart.put("2", "Heart");
Heart.put("3", "Heart");
Heart.put("4", "Heart");
Heart.put("5", "Heart");
Heart.put("6", "Heart");
Heart.put("7", "Heart");
Heart.put("8", "Heart");
Heart.put("9", "Heart");
Heart.put("10", "Heart");
System.out.print("Value: ");
val = input.next();
System.out.print("Type: ");
typ = input.next();
if(typ.equals("Heart")){
if(Heart.containsKey(val)&&Heart.containsValue(typ)){
System.out.println(val+" of "+typ+" is successfully added.\n");
}
if(Heart.containsKey(val)==false){
try{
throw new InvalidValueException();
}
catch(InvalidValueException e){
System.out.println(e.getMessage()+" 2-10, AJQK.\n");
}
}
else if(Heart.containsValue(typ)==false){
try{
throw new InvalidValueException();
}
catch(InvalidValueException e){
System.out.println(e.getMessage()+" HDSC\n");
}
}
}
Upvotes: 0
Views: 33
Reputation: 22972
If you have same value for all the keys, you should create a List<String>
of types instead of using Map
. Then you can just allow user to input type and check whether List#contains
the type or not.
If it's just an example and you will have different value for each type then,
You can just throw
Exception
with message no need to catch and print message. You can pass message in constructor.
If type
is value and val
is key
, then typ.equals("Heart")
check is redundant, as you are checking Heart.containsValue(typ)
.
So, if your typ
is not Heart
you will not able to enter the condition and if(Heart.containsKey(val)==false){
will never be true if typ
is not Heart
.
if(typ.equals("Heart"))
check.It's better to follow naming convention start variable name with lowercase.
Upvotes: 1