Convert This String to return Double - java

public static String formulaCalcularRenda = "(Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100)";
#Override
public double calcularRenda(){
return (Loja.getRendaFixa()*(1+super.getArea()/100)+super.getReceita()/100);
}
My main objective is to reuse the code, while being the formula altered by order of the user itself. I've tried something similar before, but I was uncapable to succeed, because the string has letters.
#Override
public double calcularRenda(){
return Double.parseDouble(Loja.formulaCalcularRenda);
}
Can someone help me?

As others are commenting, this is not an easy or generally wise thing to do. But if you are committed to this task, a scripting language is a much better choice for the expression evaluation. Scripting language support is built into Java and is relatively easy to use.
The Java javascript programmer guide would be a good place to start. It has examples that you should be able to adapt to your needs.

If you think about it, it doen't make too much sense for the user to write the code. So, in your opinion, what would be the best way for me, not to repeat the same code, over and over again?

Related

Efficient comparison between two POJOs to determine the extent of how similar they are

I need to make a comparison between 2 POJOs, but instead of checking for equality, I'm trying to determine how similar they are even though I know they are not the same. For instance, out of the 20 fields they have, I need to determine how many are the same/different.
ex:
public class Objekt {
private int field1;
private String field2;
private String field3;
...
private List<Integer> field4;
public Objekt () {
...
}
public compareWith (Objekt other) {
if (field1 != other.field2)
System.out.println("Field 1 is different");
if (!field2.equals(other.field2))
System.out.println("Field 2 is different");
...
// etc
}
}
Having to compare each field manually seems like a lot of extra boilerplate code, and it's also not scalable if I were to need a method similar to this with other object. I was curious if there's a solution out there to do something similar, or if anyone has any ideas on how I could make this more efficient?
New to StackOverflow, thanks for any suggestions! :)
The simple answer is: Java isn't built for "unstructured" code like you have in mind.
Meaning: there is reflection (see https://www.oracle.com/technetwork/articles/java/javareflection-1536171.html) for example that allows you to write code that inspects the fields of objects arbitrary classes. But that is extremely cumbersome and error prone, and of course: coming at high performance penalties at runtime.
There are libraries build around that though, like the https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/builder/EqualsBuilder.html that make things a bit easier to use.
But as said: the real answer is that you normally strive to avoid such designs. You should rather step back and find ways to solve the underlying problem that have better solutions in Java. Or ask yourself why you want to use a statically typed language like Java for a problem that dynamic languages are much better suited for.

Is there anything inherently wrong with long variable/method names in Java? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When is a Java method name too long?
I know this is probably is a question of personal opinion, but I want to know what's standard practice and what would be frowned upon.
One of my profs in university always seems to make his variable and method names as short as possible (getAmt() instead of getAmount) for instance.
I have no objection to this, but personally, I prefer to have mine a little longer if it adds descriptiveness so the person reading it won't have to check or refer to documentation.
For instance, we made a method that given a list of players, returns the player who scored the most goals. I made the method getPlayerWithMostGoals(), is this wrong? I toiled over choosing a way to make it shorter for awhile, but then I thought "why?". It gets the point across clearly and Eclipse makes it easy to autocomplete it when I type.
I'm just wondering if the short variable names are a piece of the past due to needing everything to be as small as possible to be efficient. Is this still a requirement?
Nothing inherently wrong, it's better to make it descriptive than cryptic. However, it's often code-smell for a method that is trying to do too much or could be refactored
Bad: getActInfPstWeek
OK: getAccountInformationForPastWeek()
Better getAccountInformation(DateRange range)
I prefer to have long variable/method names that describe what's going on. In your case, I think getPlayerWithMostGoals() is appropriate. It bothers me when I see a short variable name like "amt" and I have to transpose that in my head (into "amount").
Something like getAmt() is looks like C++ code style... In java usually are used more descriptive names.
Your professor made a good understandable method. But it's very popular word. It's not a general case. Use your "longWordStyle" style it's more java.
As per standards, longer descriptive names are advised to make it more readable and maintainable on longer term. If you use very short naming e.g. a variable as a, you will forget yourself, what that variable is meant for after sometime. This becomes more problematic in bigger programs. Though I don't see an issue in using getAmt() in place of getAmount(), but definitely getPlayerWithMostGoals() is preferable over something like getPlayer().
Long names, short names, it all depends. There are a lot of approaches and discussions but in fact a method's name should reflect its intention. This helps you to further understand the code. Take this example.
public void print(String s)
Nifty name, short, concise... isn't it? Well, actually no if there's no documentation to tell you what do you mean by "Printing". I say System.our.println is a way of printing a string but you can define printing as saving the string in a file or showing it in a dialog.
public void printInConsole(String s)
Now there are no misunderstandings. Most people can tell you that you can read the method's JavaDoc to understand it but... are you going to read a full paragraph to decide if the method you're going to use does what you need?.
IMO, methods should describe at least an action and an entity (if they're related to one). "Long" is also a perception... but really long names make the code hard to structure. It's a matter of getting the proper balance.
As a rule of thumb, I'd void abreviations and use JavaDoc to further describe a method's intention. Descriptive names can be long but the reward is both readability and a self-explainatory code.

In java is there any way to use AND instead of &&

I just want to know that is it possible in java to use
class{
private final static String AND="&&";
public static void main(String...args)
{
String str="subodh";
if(str!=null AND str.equals("subodh") )
{
System.out.println(str);
}
}
}
The above is not allowed but is there any such kind of way through we can use it by putting some extra efforts if it's please let me know or please put your openions.
Thanks
No, there's no way of changing the operators in Java - thankfully, IMO.
I suggest you learn to use Java as Java rather than trying to make it look like some other language. (Or use that other language which looks more like you want it to.)
If you're trying to do something other than bend the language to your personal preferences, please edit the question to explain what your purpose is.
No, There is no any way to use this. For that I have to go through different language.
No way to make this possible. && is operator and you cannot assign an operator to a String variable. Here AND acts like a String variable.I hope you will get it.I also do not think one will need anything like this in any situation. If possible make your motive clear why you want to this?
If you really wanted to you can implement a class to "prettify" logical operations using method chaining . And then use it something like:
PrettifyLogic.condition(str!=null).and(str.equals("subodh")).evaluate();
Though I don't personally find that more appealing to read/write. Also, good luck with operator precedence if you try something like this!
Nope, Java doesn't support doing this type of thing and I'm thankful for that! If it did we could get all sorts of things meaning && which would make existing code hard to read.
If you want to code in Java, you'll just have to stick with the way Java does things.

Standard API way to check if one array is contained in another

I have two byte[] arrays in a method like this:
private static boolean containsBytes(byte[] body, byte[] checker){
//Code you do not want to ever see here.
}
I want to, using the standard API as much as possible, determine if the series contained in the checker array exists anywhere in the body array.
Right now I'm looking at some nasty code that did a hand-crafted algorithm. The performance of the algorithm is OK, which is about all you can say for it. I'm wondering if there is a more standard api way to accomplish it. Otherwise, I know how to write a readable hand-crafted one.
To get a sense of scale here, the checker array would not be larger than 48 (probably less) and the body might be a few kb large at most.
Not in the standard library (like Jon Skeet said, probably nothing there that does this) but Guava could help you here with its method Bytes.indexOf(byte[] array, byte[] target).
boolean contained = Bytes.indexOf(body, checker) != -1;
Plus, the same method exists in the classes for the other primitive types as well.
I don't know of anything in the standard API to help you here. There may be something in a third party library, although it would potentially need to be implemented repeatedly, once for each primitive type :(
EDIT: I was going to look for Boyer-Moore, but this answer was added on my phone, and I ran out of time :)
Depending on the data and your requirements, you may find that a brute force approach is absolutely fine - and a lot simpler to implement than any of the fancier algorithms available. The simple brute force approach is generally my first port of call - it often turns out to be perfectly adequate :)
You probably already know this, but what you're trying to (re-)implement is basically a string search:
http://en.wikipedia.org/wiki/String_searching_algorithm
The old code might in fact be an implementation of one of the string search algorithms; for better performance, it might be good to implement one of the other algorithms. You didn't mention how often this method is going to be called, which would help to decide whether it's worth doing that.
The collections framework can both cheaply wrap an array in the List interface and search for a sublist. I think this would work reasonably well:
import java.util.Arrays;
import java.util.Collections;
boolean found = Collections.indexOfSubList(Arrays.asList(body), Arrays.asList(checker) >= 0;

Compute percentage for bigdecimals

I haven't found any native method to do this, so I created my own in a helper class:
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(new BigDecimal(100));
}
But I don't quite like it, I wonder if the API has something similar. The Number class (ancestor of BigDecimal) would be a nice place.
I don't think there is an API for that (I never needed it).
Your solution seams good to me, maybe you just add the constant ONE_HUNDRED:
public static final BigDecimal ONE_HUNDRED = new BigDecimal(100);
public static BigDecimal percentage(BigDecimal base, BigDecimal pct){
return base.multiply(pct).divide(ONE_HUNDRED);
}
probably not that much gain, only if called very often
eventually put it in some Util class...
You may want to implement the division by 100 using BigDecimal.scaleByPowerOfTen(-2).
It adds up if you do it a million times. It is much faster in my experience.
There is also a similar method BigDecimal.movePointLeft(2) - see the other thread for details and decide which one works better for you.
Feel free to subclass BigDecimal and add that method. Beyond that, what do you expect? You know where to find the API and confirm that the class you would like to have that method doesn't. Personally, I'd say the functionality is so trivial that there wouldn't be much of a point in having it in the standard API.
See also DecimalFormat. You can use the parent's factory method NumberFormat.getPercentInstance() as shown here, here, et al.

Categories

Resources