Dynamic calculation over dataset by providing logic externally [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I am doing some mathematical operation on a data set. As per the requirement of the project, the mathematical formula/logic can be changed at any time. So I am thinking to keep these formals out from the Java code, may be in config file. Below is the sample config file-
formula.properties file-
formula_a=(a+b)/(7*c+b^2)
formula_b=(a^(1/2)-formula_a*13)
formula_c=spilt_time(formula_b,a,b)
Calculator.java (A dummy Java file, which may not be correct as Its for demo purpose only)
public class Calculator
{
private final static String FORMULA_A = "formula_a";
private final static String FORMULA_B = "formula_b";
private final static String FORMULA_C = "formula_c";
public static void main(String[] args)
{
long a = 1738342634L;
long b = 273562347895L;
long c = 89346755249L;
long ansFromFormulaA = applyFormulaFromConfig(FORMULA_A, new long[] { a, b, c });
long ansFromFormulaB = applyFormulaFromConfig(FORMULA_B, new long[] { a, b, c });
long ansFromFormulaC = applyFormulaFromConfig(FORMULA_C, new long[] { a, b });
}
// spilt_time is used in formula_c
public static long[] spilt_time(long[] params)
{
final long[] split = new long[2];
// Some logic here which is applied on params array and answer is pushed
// into split array
return split;
}
private static long applyFormulaFromConfig(String formulaName, long[] params)
{
long ans = 0L;
// Read formula from property file here and apply the params over it and
// return the answer
return ans;
}
}
Please help me to design a solution for this.

Ok here is one:
Define your functions in JavaScript in a separate js-file outside your application. Might look like this:
function myFunction1(x, y, z) {
return x * y + z;
}
Now you can evaluate these script via the Java ScriptEngine and call those functions by name, passing them your params.
Have a look: http://www.wondee.info/2013/10/30/the-scriptengine-bindings/
edit:
Propeterties file:
function1=x + y * z
function2=x * x
read the functions into formula variable... and...
You can put your functions in a String and put it inside a function body like that:
String formula = readFromProperties("function1");
String myFunctionScript = String.format("function myFunction(x, y, z) { return %s ;}", formula);

Related

using two java files with two class compilation error [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am new to java, trying to learn by making mini projects right now. I have two classes and when I run my program I have this error : Cannot make a static reference to the non-static field Game.balance.
Not quite sure why I am getting it and wondering if anyone knows any fixes.
import java.util.Random;
import java.util.Scanner;
public class Mainone {
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.operation);
}
}
this is the second class below (new file)
import java.util.Random;
public class Game {
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
System.out.print(Game.operation);
change to
System.out.print(print.operation);
In java, you can't access Object field values by Class directly. But you can access the static field by using Class.
public class Game {
public static String ABC = "1"; // can access by Game.ABC
int balance = 1000;
int operationAmount;
int randOperation;
boolean ad = true;
public Game(int b, int o, int r, boolean a) {
balance = b;
operationAmount = o;
randOperation = r;
ad = a;
}
}
public static void main(String[] args) {
System.out.println("You have $1000. I hope you make good choices!");
Scanner user = new Scanner(System.in);
Game print = new Game(1000,0,0,true);
System.out.print(Game.ABC); // here you can access the static field
}
you are trying to call Game.operation. Instead of this try print.operation.
I assume operation is function in class Game.
Here the state is managed by the print object of Game class.
Please call System.out.print(print.operation);

Java 8 Stream | Add a value of the stream to another List/Collection without using foreach or any terminal Operation [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
So far i tried to add values from a stream to a list with peek() but later I found out that peek() is only used "to support debugging, where you want to see the elements as they flow past a certain point in a pipeline".
Now my question is whats the coding-convention here ?
Do I map it in a second stream or can I map it one String like my Code with Peek() ?
final int range = 9;
List <String> help = new ArrayList<String>();
//random numbers to fill help
for(int i = 5;i< range;i++)
{
help.add(String.valueOf(i+(i*2)+(i*(i+2))) );
}
List<Test> others = new LinkedList<>();
List<Test> tests = help.stream().map(s-> new Test(s,(int) Integer.valueOf("10")))
.peek(t->System.out.println(t.getText()))
.peek(t-> others.add(t)).collect(Collectors.toList());
The class Test looks like this:
public class Test
{
String text;
int id;
public Test(String text, int id) {
this.text = text;
this.id = id;
}
public String getText() {
return text;
}
public int getId() {
return id;
}
}
You could add that functionality to the lambda in the mapping part:
List<Test> tests = help.stream().map(
s-> {
Test t = new Test(s,(int) Integer.valueOf("10")));
System.out.println(t.getText());
others.add(t)
return t;
}
.collect(Collectors.toList());
That simply moves your extra steps into an existing step, avoiding any further loops etc

is there any way to call a variable from a specific if statement? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
ok so I need to make this program that involves the gravity constant. but i let the user decide that
double g;
String unit;
if (n == JOptionPane.YES_OPTION) {
g = 9.8;
System.out.print(g);
unit = "meters/s";
}
else {
g = 32;
System.out.print(g);
unit = "feet/s";
}
and then i put it into this formula OUTSIDE of the if statement
double ycoord = (velo0*sinF*time)-((g)((time*time)))/2;
i know that the scope of the if statement ends after the last curly brace but i'm wondering if there is any way to call for one of the values of g
thanks in advance!
If you have the above bit of code inside a method, then it's scope is restricted to that method. However you can create a class variable g and set it within your method.
Public Class Test {
//g can only be accessed within this class
//however you can access g with the following getter method
private double g;
public static void setG() {
this.g = 9.5;
}
public static void setGWithInput(Double input) {
this.g = input;
}
public static void printG() {
//you can access the value of g anywhere from your class
System.out.println("Value of g is" + this.g);
}
//create a public getter to access the value of g form outside the class
public double getG() {
return this.g;
}
}
As long as your statement containing your "formula" is within the same function/code block as the declaration of 'g', you can reference g as part of that statement.
You should really provide more details and describe your problem more explicitly.

Why doesnt string.equals("astring") work? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
Why don't I get 20 after delivering e.g. "Obsidian" to Test(String pStr) if I call getMatInt() ?
Also tried .toString() after all String-declariations, also declarated e.g. "Obsidian" as new String a. Nothing works.
getBonus is aways returning a 0 instead of a 20/30/... .
I already tried "Obsidian" and "obsidian", both doesnt work for me ...
public class test
{
private String str;
private int matInt;
private int bonus;
private int magic;
public test(int pMagic, String pStr)
{
int magic = pMagic;
str = pStr;
}
private void materialEquals()
{
if(str.equals("Obsidian"))
{
matInt = 20;
}
.....
}
private void calcBonus()
{
materialEquals();
bonus = magic * matInt;
}
public int getBonus()
{
calcBonus();
return bonus;
}
}
try:
public int getMatInt()
{
materialEquals();
return matInt;
}
There is no reason for this in your constructor: str = new String(pStr);, just use str = pStr.
In fact, you might be better off setting matInt in your constructor:
public test(String pStr)
{
str = pStr;
materialEquals();
}
And depending on how many materials you have, you might want to look into using enumeration.
Ok after your edits:
public int getBonus()
{
calcBonus(); //bonus won't be calculated otherwise
return bonus;
}
After further edits:
Your constructor is wrong, you're not initializing int magic. Try this constructor instead.
public test(int pMagic, String pStr)
{
this.magic = pMagic; //int magic = pMagic was a new variable only in the constructor scope
this.str = pStr;
calcBonus();
}
Also you might as well calculate the bonus on construction.
You will need to call materialEquals() so that 20 can be assigned to matInt upon equals comparison, as integers are always initialized to default value 0 upon declaration.

How to write switch statements based on 3 variables? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I have a lecagy validator class that I'd like to work with. It gives all permutations to validate 1-3 different fields.
class Validator {
Checker Validator.A, Validator.B, Validator.C;
Checker[] ABC = {Validator.A, Validator.B, Validator.C};
Checker[] AB = {Validator.A, Validator.B};
Checker[] BC = {Validator.B, Validator.C};
Checker[] AC = {Validator.A, Validator.C};
}
I don't have any influence on this class. But have to use one of these Checkers.
I want to chose the needed validator based on the fields that are not empty.
Therefore, I wrote the following switch statemend. But to me it seems to be very ugly. How could I improve this?
String a, b, c;
boolean isA = !a.isEmpty();
boolean isB = !b.isEmpty();
boolean isC = !c.isEmpty();
Checker[] checker;
if (isA && isB && isC) {
checker = Validator.ABC;
} else if (isA && isB) {
checker = Validator.AB;
} else if (isA && isC) {
checker = Validator.AC;
} else if (isB && isC) {
checker = Validator.BC;
} else if (isA) {
checker = Validator.A;
} else if (isB) {
checker = Validator.B;
} else if (isC) {
checker = Validator.C;
}
How about this?
List<Checker> checkers = new ArrayList<Checker>();
if (!a.isEmpty()) checkers.add(Validator.A);
if (!b.isEmpty()) checkers.add(Validator.B);
if (!c.isEmpty()) checkers.add(Validator.C);
Checker[] checker = checkers.toArray(new Checker[checkers.size()]);
Alternatively you could do it this way
List<Checker> list = new ArrayList<>();
if (!a.isEmpty()) {
list.add(Validator.A);
}
if (!b.isEmpty()) {
list.add(Validator.B);
}
if (!c.isEmpty()) {
list.add(Validator.C);
}
Checker[] checker = list.toArray(new Checker[list.size()]);
You could simplify it using reflection, approximately like this (haven't actually compiled, but should be close enough):
String name = (a? "A":"") + (b? "B":"") + (c? "C":"");
checker = Validator.class.getField(name).get();
if you really want to do it, you have to convert whole your input to "case'able" data. e.g int
2 ^((int) a) * 3^((int) b) * 5^((int) c)
or to string (since java 7)
but, don't do it. it's ugly. create a collection and fill it with necessary checkers. as showed by Chris King
You can do the whole thing with enums. It adds a powerful extendibility component.
enum Checker {
A, B, C;
public boolean check () {
// You do this.
return true;
}
}
enum Validator{
ABC(Checker.A, Checker.B, Checker.C),
AB(Checker.A, Checker.B),
BC(Checker.B, Checker.C),
AC(Checker.A, Checker.C),
A(Checker.A),
B(Checker.B),
C(Checker.C),
;
final Checker[] checkers;
Validator(Checker ... checkers) {
this.checkers = checkers;
}
boolean validate(Collection a, Collection b, Collection c) {
// Grow the name of the validator from the data.
String name = (!a.isEmpty()?"A":"") +
(!b.isEmpty()?"B":"") +
(!c.isEmpty()?"C":"");
// The final result.
boolean checksOut = true;
// TODO: Handle the all-empty scenario.
if ( name.length() > 0 ) {
// Pull the checks array out of the correct validator.
Checker [] checks = Validator.valueOf(name).checkers;
for ( Checker check : checks ) {
// Do all of the checks defined.
checksOut &= check.check();
}
}
return checksOut;
}
}

Categories

Resources