I may get result of any of the type , so i am defining enum this way
public enum Result
{
1, 2,3, 4,5, 6,7, 8
}
String resultvalue = calculateResult();
switch (Result .valueOf(resultvalue ))
{
}
But i am geting error at the Enum Declaration itself saying Mispalced Constructors .
Could anybody please help me
Those aren't valid identifiers for enum values, basically. You'll need to prefix them with a letter or _. You'll also need to make the identifiers unique - currently you've got 0010 four times...
Once you've sorted that out, the rest should probably be okay - but if you have any more problems, please post a short but complete program, rather than snippets.
0001 is not a valid Java identifier. A Java Identifier must not start with a digit.
Although I don't understand what you want to achieve and why you have duplicates. Something like that (maybe using an int instead of String) should work.
public enum Result {
One( "0001"),
Two( "0010")
...
private String val;
private Result(String val) {
this.val = val;
}
}
I an not sure why calcuate result would return a String. I would return a int here but...
String resultvalue = calculateResult();
switch (Integer.parseInt(resultvalue)) {
case 0b0001:
case 0b0010:
case 0b0110:
case 0b1010:
case 0b1100:
}
What is it that you are trying to achieve? If you need to:
parse an integer from a string, then
check that it's from a certain set of values, and finally
switch on its value,
then you don't need an enum. Just do it with Integer.parseInt(), Set.contains(), and switch.
Related
I want to use Guava's Maps.difference in java 11 to verify data from Json String which I mapped into a Map.
What I have after a call (with different uid each time) :
{"uid":"31a340bc-e5ed-440c-8726-34c54dea902a","name":"Jean"}
I want to verify that uid is correctly generated and name is "Jean" using a pattern like this :
{"uid":"*","name":"Jean"}
Of course Maps.difference returns a difference in uid value...
Is it possible to specify a wildcard in my verifying pattern so that Maps.difference returns no differences ?
Thanks in advance.
Assuming you mean Guava's Maps.difference: yes, use the difference(left, right, valueEquivalence) overload:
Maps.difference(left, right, new Equivalence<String>() {
#Override public boolean doEquivalent(String a, String b) {
return "*".equals(a) || "*".equals(b) || Objects.equals(a, b);
}
// You have to hash all strings to the same thing because you
// don't know if the current item is a "*", or its corresponding
// item is a "*". But actually it doesn't matter, because I don't
// think it's invoked in difference.
#Override public int doHash(String s) { return 0; }
});
I'm sure this is a small, stupid error that I just can't see.
I'm getting a compiling error in this code:
private String setQuestions(){
int match = Math.floor(Math.random()*cities.length); }
in my length.
Compiling error is:
"Cannot find symbol
symbol: variable length
location: variable cities of type ArrrayList "
How can I fix this? I do want to use Math.random();
Also not sure if this makes a difference, but this is is being done within a String method.
Thanks in advance!
if cities is of type ArrayList you have to use cities.size() instead of cities.length.
There are a couple of errors here.
First: If your method is not void is because you're gonna return something, in your method you should return a String.
Second: The result of Math.floor(Math.random()*cities.length) it's a double, so you can't store on a simple int, you should parse it or just change the int for double
Third: If you wanna return that match variable you should parse it to a String like you're declaring or just change the declaration to double.
So, the easier fix would be just changing the string and int for double and return it like this:
private static double setQuestions(){
double match = Math.floor(Math.random()*cities.length);
return match;
}
Remember if you want to use the double returned you should store it when you call it, like this:
double result = setQuestions();
Hope it helps!
The code has three problems:
First, the variable "cities" is an ArrayList, as the compiller error wrote. ArrayList is a Collection which implements the interface List. The size of any implementations of List is accessable by method size(). Than, you should change cities.length by cities.size() or you turn cities as array.
Second, you defined the variable "match" as an int value but method floor from Math return a double. If you really want "match" to be a int, than you can use the cast against the method floor, that is, you code become: int match = (int) Math.random()*cities.size();
Third, your method requires an String as return, than you should return the String object correctly.
Is there any way of converting an enum into a constant expression?
I want my switch operator to choose among the values of an enum, but I got a compile error "case expressions must be constant expressions", so I tried to declare it in a variable:
final int REG = MyEnum.REG.getIndex().intValue();
switch (service.getIndex()) {
case REG:
But I still get the same error. According to Oracle's documentation http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
A compile-time constant expression is an expression denoting a value
of primitive type or a String that does not complete abruptly and is
composed using only the following:
•Literals of primitive type and literals of type String
So it isn't working because I'm not using a literal. I think I will have to declare it as:
final int REG = 8;
But it'd be much better to link it to the enum. Is there any way of doing this?
EDIT
Turns out I don't need to use any final variable. It is just as simple as:
switch (service) {
case REG:
It didn't occur to me till I saw Andrea's comment. Thanks for your answers.
If possible, modify your getIndex() method so that it returns an enum instead of an integer. If this is not possible, you need to map the index to an enum element:
Given the following enum:
public enum Index {
ONE,
TWO,
THREE
}
you can map your index to an enum element by using
Index.values()[index]
Given your method Integer getIndex(), you can then do something like
switch(Index.values()[getIndex()])
case ONE : ...
break;
case TWO : ...
break;
case THREE : ...
break;
}
Note that this might throw an ArrayIndexOutOfBoundsException if you try to access an index within the enum which is larger than the number of enum elements (e.g. in the sample above, if getIndex() returns a value > 2).
I would encapsulate the expression Index.values()[getIndex()] into an enum method like valueOf(int index), similar to the default valueOf(String s). You can then also handle the valid array index check there (and for example return a special enum value if the index is out of range). Similarly, you can then also convert discrete values which have special meanings:
public enum Index {
ZERO,
ONE,
TWO,
THREE,
REG,
INVALID;
public static Index valueOf(int index) {
if (index == 8) {
return REG;
}
if (index >= values().length) {
return INVALID;
}
return values()[index];
}
}
This is an example only - in any case, it generally depends on the range of values you get from your getIndex() method, and how you want to map them to the enum elements.
You can then use it like
switch(Index.valueOf(service.getIndex())) {
case ZERO : ... break;
...
case REG : ... break;
...
}
See also Cast Int to enum in Java for some additional information (especially the hint that values() is an expensive operation since it needs to return a copy of the array each time it is called).
If you want specific numeral values assigned to enum constacts go like this
enum MyReg {
REG(8), OTHER(13);
public final int value;
MyReg(int value) {
this.value=value;
}
}
You then use it like this:
class Test {
public static void main(String[] args) {
MyReg reg = MyReg.REG;
switch (reg) {
case OTHER:
System.out.println(reg.value);
break;
case REG:
System.out.println(reg.value);
break;
}
}
}
I have this coding inside my java file .
This code basically receives an int value and sets a char value for an Object
Student st = new Student();
if (attributeName.equals("Grade")) {
int sidevalue = Integer.parseInt(attribute.getValue()); // This returns an int value , and this value needs to be converted into char later as shown
if(sidevalue==1)
st.grade=1;
else if(sidevalue==2)
st.grade=2;
else if(sidevalue==5)
st.grade=3;
}
class Student
{
char grade ;
}
Integer.parseInt throws an exception, if the attribute name is not a number. Catch it and handle the error.
The Student class should be made public and go to a separate java file
The grade field should be an int (your passing numbers)
Alternatively - if you need to store chars, you may have to say st.grade = '1'; (to pass a '1' instead of a 0x01)
The grade field should be private, use getGrade and setGrade methods to read an write the property
I don't understand the meaning of "sidevalue" - if it does not have a well known meaning in the domains context, then consider renaming it.
The local variable st should be renamed to student
the if-else-if chain could be replaced by a switch-case statement.
You could use a map
Map<Integer, Integer> gradeMappings = new HashMap<Integer, Integer>();
gradeMappings.put(1,1);
gradeMappings.put(2,2);
gradeMappings.put(3,5);
if (attributeName.equals("Grade")) {
int sidevalue = Integer.parseInt(attribute.getValue());
st.grade = gradeMappings.get(sidevalue);
}
In real life, you'd want to add some exception checking for when the attribute value is not a key in the map. You could also make the default behaviour to use the parsed attribute value as the grade, and only override the value if an appropriate entry is present in the map.
A switch case check here statement could avoid multiple if else indentation!
switch(sidevalue){
case 1: st.grade = 1;
break;
case 2: st.grade = 2;
break;
case 5: st.grade = 3;
break;
default: break;
}
There is no significant execution difference in running between if-else and switch.
Observed differences may be due to the sample space of the particular code you are running.
In the little code snippet you provide there is not a best choice, except that switch statement provides improved readability.
Check these links for further details:
Is "else if" faster than "switch() case"?
if-else vs switch
When to use If-else if-else over switch statments and vice versa
Look into the control keyword switch. This will somewhat alleviate this style of coding.
The best way to improve this code is to write a test for it.
Problems at this stage: 'grade' should be private.
Grade is probably a first class object.
How do you plan to support other grades? Say 4 or 6? What happens if sidevalue comes back with invalid value?
Others have suggested minor syntax changes (which may be helpful), but I think you are best thinking about this in an object-oriented sense, encapsulating this logic into the student class itself, that way you will only need to write it once. If you need different logic for different scenarios you can always use inheritance and override setGrade.
Student st = new Student();
st.setGrade(Integer.parseInt(attribute.getValue()))
class Student{
private char grade ;
public setGrade(int sidevalue){
if(sidevalue==1)
grade=1;
else if(sidevalue==2)
grade=2;
else if(sidevalue==5)
grade=3;
else
throw new IllegalArgumentException();
}
public char getGrade(){
return grade;
}
}
If you have canonical String values stored in attribute.getValue() then you can remove integer parsing and simply compare string values
String sidevalue=attribute.getValue()
if(sidevalue=="1"){
}else if(sidevalue=="2"){
}...
Refer to String.intern method for more details. This will help improve performance of your program.
1) Start using coding formats. Its advisable to use objStudent rather than some 'st'.
2) There is no use of creating int sidevalue. Directly use a switch case as give below:
switch(Integer.parseInt(attribute.getValue()))
{
case 1:
----
.
.
.
and so on...
}
HashMap<String, String> config = Feeds.config;
String num = config.get("NumOfFeeds");
System.out.println(num);
feedsAmount = ((Integer)num).intValue();
System.out.println(feedsAmount);
I've also tried Integer.parseInt(num) and Integer.decode(num) and Integer.valueof(bu)
Results as follows: 40
Exception in thread "main" java.lang.NumberFormatException: For input string:"40"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
at java.lang.Integer.parseInt(Integer.java:499)
at fetch_RSS.<init>(fetch_RSS.java:40)
at testing.main(testing.java:27)
The problem was caused by different encoding from the txt file I'm reading from and the encoding in Elipse which is the macRoman by default.
The correct way of working is this:
String num = config.get("NumOfFeeds");
int feeds = Integer.parseInt(num);
This, only when you are sure that the String is representing a number the valid way.
-30 // correct
0 // correct
2000 // correct
"40" // invalid
40 // valid
2.000 // invalid
2.000.000 // invalid
20,0 // invalid
2,000,000 // invalid
Your exception got raised in Integer.java:458.
Looking into the source code of Integer I see that some characters of your String "40" returned a negative value (most probably -1) for Character.digit(s.charAt(i++), radix) where i is iterating over String's characters and radix is 10.
This should not happen normally. But it happens when the String is "4o" and not "40" like #Løkling's wild guess in the comments.
You should debug here to see what really happens.
Of course you can't cast from String to Integer. A String is not a Integer, and Integer is not a String.
You have to use int i = Integer.parseInt(..). It works if the string is a properly formatted integer.
For a cast to succeed in Java, the reference being cast must point to an object that is actually an instance of the type being cast to. A reference to String can't be cast to Integer because an object couldn't possibly be both things.
(This is somewhat unlike a cast in C, which is basically just saying, reinterpret the data stored here according to a different datatype. It would still be incorrect in C to use casting as a method to convert a string representing a number to a numeric value.)
Integer.parseInt is what you are looking for here. What problem are you having with it?
Remember : In java, we can only cast between objects if they are EXPLICITLY of the same type ! In other languages , like python, we can do the casting you requested here, because those languages allow "duck typing".
You must use Integer.parseInt("1234"), to create an Integer object from a String.
Alternatively you could create an Object wrapper to your data :
class MyObject
{
Object input;
public MyObject(Object input)
{
this.input=input;
}
public Integer getInt()
{
return Integer.parseInt(input.toString());
}
public String getString()
{
return input.toString();
}
}
This would be overkill for your simple problem, however :)