Is there a better way to write this constructor which has multiple if statements and multiple arguments? I'm a noob to programming so any leads would be helpful.
public Latency(final double full, final double cpuOne, final double cpuTwo, final double cpuThree, final double cpuFour) {
if (full > 10.0 || (full <= 0.0)) {
throw new IllegalArgumentException("Must check the values");
}
this.full = full;
if (cpuOne == 0 && cpuTwo == 0 && cpuThree == 0 && cpuFour == 0) {
throw new IllegalArgumentException("not all can be zero");
} else {
if (cpuOne == 0.5) {
this.cpuOne = full;
} else {
this.cpuOne = cpuOne;
}
if (cpuTwo == 0.5) {
this.cpuTwo = full;
} else {
this.cpuTwo = cpuTwo;
}
if (cpuThree == 0.5) {
this.cpuThree = full;
} else {
this.cpuThree = cpuThree;
}
if (cpuFour == 0.5) {
this.cpuFour = full;
} else {
this.cpuFour = cpuFour;
}
}
}
I think this code doesn't need much of context as it is pretty straight forward.
I found out that we can't use switch statements for type double. How to optimize this?
There are a number of possible ways of refactoring the code that you've written, and there are pros and cons of each one. Here are some ideas.
Idea One - use the conditional operator
You could replace the else block with code that looks like this. This is just effectively a shorter way of writing each of the inner if/else blocks. Many people find this kind of form more readable than a bunch of verbose if/else blocks, but it takes some time to get used to it.
this.cpuOne = cpuOne == 0.5 ? full : cpuOne;
this.cpuTwo = cpuTwo == 0.5 ? full : cpuTwo;
this.cpuThree = cpuThree == 0.5 ? full : cpuThree;
this.cpuFour = cpuFour == 0.5 ? full : cpuFour;
Idea Two - move common functionality to its own method
You could have a method something like this
private static double changeHalfToFull(double value, double full) {
if (value == 0.5) {
return full;
} else {
return value;
}
}
then call it within your constructor, something like this.
this.cpuOne = changeHalfToFull(cpuOne);
this.cpuTwo = changeHalfToFull(cpuTwo);
this.cpuThree = changeHalfToFull(cpuThree);
this.cpuFour = changeHalfToFull(cpuFour);
This has the advantage that the key logic is expressed only once, so it's less error prone than repeating code over and over.
Idea Three - use arrays
You could use an array of four elements in the field that stores these values. You could also use an array for the constructor parameter. This has a huge advantage - it indicates that the four CPU values are somehow all "the same". In other words, there's nothing special about cpuOne compared to cpuTwo, for example. That kind of messaging within your code has real value to someone trying to understand this.
public Latency(final double full, final double[] cpuValues) {
// validation conditions go here ...
this.cpuValues = new double[4];
for (int index = 0; index <= 3; index++) {
if (cpuValues[index] == 0.5) {
this.cpuValues[index] = full;
} else {
this.cpuValues[index] = cpuValues[index];
}
}
}
Or a combination
You could use some combination of all these ideas. For example, you might have something like this, which combines all three of the above ideas.
public Latency(final double full, final double[] cpuValues) {
// validation conditions go here ...
this.cpuValues = new double[4];
for (int index = 0; index <= 3; index++) {
this.cpuValues[index] = changeHalfToFull(cpuValues[index]);
}
}
private static double changeHalfToFull(double value, double full) {
return value == 0.5 ? full : value;
}
There are obviously other possibilities. There is no single correct answer to this question. You need to choose what you're comfortable with, and what makes sense in the larger context of your project.
DRY - Don't Repeat Yourself
Each if is essentially the same. Put it in a separate method and call the method once for each cpu* variable.
public class Latency {
private double full;
private double cpuOne;
private double cpuTwo;
private double cpuThree;
private double cpuFour;
public Latency(final double full,
final double cpuOne,
final double cpuTwo,
final double cpuThree,
final double cpuFour) {
if (full > 10.0 || (full <= 0.0)) {
throw new IllegalArgumentException("Must check the values");
}
this.full = full;
if (cpuOne == 0 && cpuTwo == 0 && cpuThree == 0 && cpuFour == 0) {
throw new IllegalArgumentException("not all can be zero");
}
else {
this.cpuOne = initCpu(cpuOne);
this.cpuTwo = initCpu(cpuTwo);
this.cpuThree = initCpu(cpuThree);
this.cpuFour = initCpu(cpuFour);
}
}
private double initCpu(double cpu) {
return cpu == 0.5 ? full : cpu;
}
public static void main(String[] arg) {
new Latency(9.99, 8.0, 7.0, 6.0, 0.5);
}
}
Related
Could you please help me find a solution for my code? I'm making a new Android app in which I need to make some calculations and the scenario is the following:
There are four fields to be calculated. Two EditText (number decimal) field are obligatory and the other two are optional, BUT, if the optional fields are filled, then it needs to be in the calculation, otherwise only the obligatory fields will be used.
Right now I'm totally OK with calculating the obligatory fields but when I try some if-else clause to include the optional fields in the calculation, the app goes bananas.
I'm not sure where I should make this two-step option, if I should use boolean to check the option field condition, if I just keep using if-else...
The problem is not the calculatin itself, but having two ways for the code to follow: One using only the obligatory fields if nothing else is inserted and the other one using all four fields.
Thanks everyone!
Code below is only using the two obligatory fields.
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
double valorResultado = valorEtanol / valorGasolina;
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
You almost got it. What happens now, since you have an if-if-elseconstruction, it considers the first if statement to be seperate from the if-else block below. That is to say, if editEtanol.length() == 0 evaluates to false, it will execute the else block below, even if editGasolina.length() == 0 evaluates to true.
Changing the line if (editEtanol.length() == 0) { to else if (editEtanol.length() == 0) { should already help alot. Hope that helps!
public void calcularResultado(View view) {
//check for blank values in obligatory fields
if (editGasolina.length() == 0) {
editGasolina.setError("Insira o valor");
}
if (editEtanol.length() == 0) {
editEtanol.setError("Insira o valor");
//runs the code
} else {
double valorGasolina = Double.parseDouble(editGasolina.getText().toString());
double valorEtanol = Double.parseDouble(editEtanol.getText().toString());
boolean optionalField1Used = optionalEditText1.length() != 0;
boolean optionalField2Used = optionalEditText2.length() != 0;
double valorResultado = 0;
if (!optionalField1Used && !optionalField2Used) {
valorResultado = valorEtanol / valorGasolina;
} else if (optionalField1Used && !optionalField2Used) {
valorResultado = //some other calculation
} else if (!optionalField1Used && optionalField2Used) {
valorResultado = //yet another calculation
} else {
valorResultado = //calculation if both optional fields used
}
double porcentagem = (valorResultado) * 100;
String valorResultadoTexto = Double.toString(porcentagem);
valorResultadoTexto = String.format("%.2f", porcentagem);
if (valorResultado >= 0.7) {
textResultado.setText("GASOLINA");
textRendimento.setText(valorResultadoTexto + "%");
} else {
textResultado.setText("ETANOL");
textRendimento.setText(valorResultadoTexto + "%");
}
Let us assume that the optional fields are called edit1 and edit2. I also assume that in order to use the alternative computation, both optional values must be present.
To enhance code clarity, I would define two Boolean variables to explicitly indicate whether the mandatory and optional fields have values. Something like the following.
public void calcularResultado(View view) {
var mandatoryValues = true;
var optionalValues = false;
if (editGasolina.length() == 0 {
editGasolina.setError("Insira o valor");
mandatoryValues = false;
}
if (editEtanol.length() == 0 {
editEtanol.setError("Insira o valor");
mandatoryValues = false;
}
if (edit1.length() > 0 && edit2.length() > 0) {
optionalValues = true;
}
if (mandatoryValues) {
if (optionalValues) {
// do alternative computation
} else {
// do computation for mandatory values only
}
}
}
Note that if either mandatory value is absent, no computation is performed.
Hope it helps - Carlos
I've been wanting to calculate pi with the Gregory-Leibniz series, and there's something wrong with it. I'm a bit of a starter to Java, so this may not be a hard question to answer. I don't know what's going on, so can somebody help me please?
Code so far:
package com.waitdev.pi;
public class Pi {
static int pi = 0;
public static void main(String[] args) {
for (int i = 1; i < 51; i++) {
if (isOdd(i)) {
pi = pi+(4/((i*2)-1));
// System.out.println(i);
} else {
pi = pi-(4/(i*2)-1);
// System.out.println(i);
}
}
System.out.println(pi);
}
private static boolean isOdd(int n) {
if (n % 2 == 1) {
return true;
} else {
return false;
}
}
}
FYI: The output for this is 28.
Thanks.
You are missing a parenthesis in your else block, and you need to force float calculation by e.g writing 4.0 instead of 4.
It should read:
if (isOdd(i)) {
pi = pi+(4.0/((i*2)-1));
// System.out.println(i);
} else {
pi = pi-(4.0/((i*2)-1));
// System.out.println(i);
}
You also need to use a float or a double for pi.
Extra - as for your isOdd method, it could be simplified like:
private static boolean isOdd(int n) {
return (n % 2 == 1)
}
But this does not influence the result.
First off: an int is an integer, whole number. you want to change it to:
static double pi = 0;
Otherwise the answer always gets rounded down to a whole number.
Secondly, you are missing parenthesis in your else statement:
} else {
pi = pi-(4/((i*2)-1));
}
If you want to be completely safe, change your integers in the if and else clause to doubles:
if (isOdd(i)) {
pi = pi+(4.0/((i*2.0)-1.0));
// System.out.println(i);
} else {
pi = pi-(4.0/((i*2.0)-1.0));
// System.out.println(i);
}
But that shouldn't be neccessary
I just discovered the project euler website, I have done challenges 1 and 2 and have just started number 3 in java... here is my code so far:
import java.util.ArrayList;
public class IntegerFactorise {
private static int value = 13195;
private static ArrayList<Integer> primeFactors = new ArrayList<Integer>();
private static int maxPrime = 0;
/**
* Check whether a give number is prime or not
* return boolean
*/
public static boolean isPrimeNumber(double num) {
for(int i = 2; i < num; i++) {
if(num % i == 0) {
return false;
}
}
return true;
}
/*Multiply all of the prime factors in the list of prime factors*/
public static int multiplyPrimeFactors() {
int ans = 1;
for(Integer i : primeFactors) {
ans *= i;
}
return ans;
}
/*Find the maximum prime number in the list of prime numbers*/
public static void findMaxPrime() {
int max = 0;
for(Integer i : primeFactors) {
if(i > max) {
max = i;
}
}
maxPrime = max;;
}
/**
* Find all of the prime factors for a number given the first
* prime factor
*/
public static boolean findPrimeFactors(int num) {
for(int i = 2; i <= num; i++) {
if(isPrimeNumber(i) && num % i == 0 && i == num) {
//could not possibly go further
primeFactors.add(num);
break;
}
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
else {
return false;
}
}
/*start here*/
public static void main(String[] args) {
boolean found = false;
for(int i = 2; i < value; i++) {
if(isPrimeNumber(i) && value % i == 0) {
primeFactors.add(i);
found = findPrimeFactors(value / i);
if(found == true) {
findMaxPrime();
System.out.println(maxPrime);
break;
}
}
}
}
}
I am not using the large number they ask me to use yet, I am testing my code with some smaller numbers, with 13195 (their example) i get down to 29 in this bit of my code:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
findPrimeFactors(num / i);
}
}
int sumOfPrimes = multiplyPrimeFactors();
if(sumOfPrimes == value) {
return true;
}
It gets to the break statement then finally the check and then the return statement.
I am expecting the program to go back to the main method after my return statement, but it jumps up to:
findPrimeFactors(num / i);
and tries to finish the iteration...I guess my understanding is a flawed here, could someone explain to me why it is behaving like this? I can't wait to finish it of :) I'll find a more efficient way of doing it after I know I can get this inefficient one working.
You are using recursion, which means that a function will call itself.
So, if we trace what your function calls are when you call return, we will have something like that:
IntegerFactorise.main()
|-> IntegerFactorise.findPrimeFactors(2639)
|-> IntegerFactorise.findPrimeFactors(377)
|-> IntegerFactorise.findPrimeFactors(29) -> return true;
So, when you return in the last findPrimeFactors(), you will only return from this call, not from all the stack of calls, and the execution of the previous findPrimeFactors() will continue just after the point where you called findPrimeFactors().
If you want to return from all the stack of calls, you have to modify your code to do something like that:
else if(isPrimeNumber(i) && num % i == 0) {
primeFactors.add(i);
return findPrimeFactors(num / i);
}
So that when the last findPrimeFactors() returns, all the previous findPrimeFactors() which called it will return too.
I think the problem is that you are ignoring the return value from your recursive call to findPrimeFactors().
Let's walk through this. We start with the initial call to findPrimeFactors that happens in main. We then enter the for loop as it's the first thing in that method. Now let's say at some point we get into the else statement and thus recursively call frindPrimeFactors(num / i). This will suspend the looping, but as this recursive call starts to run you enter the for loop again (remember, the previous loop is merely paused and not finished looping yet). This time around you encounter the break, which allows this recursive call to finish out, returning true of false. When that happens you are now back to the original loop. At this point the original loop continues even if the recursive call returned true. So, you might try something like this:
if (findPrimeFactors(num / i))
return true;
I'm assuming that you need to continue looping if the recursive call returned false. If you should always finish looping upon return (whether true or false) then try this:
return findPrimeFactors(num / i);
I used the following code in my class with the intention of doing one round of recursion (specifically creating an object within an object of the same type). Well, that one round of recursion is now like 200 rounds of recursion... So that messes a lot of stuff up. The following code is where I call the recursion:
//Find Solute
try{if(iterations == 0){ //RECONDITION::: iterations is equal to zero at start of program and is static!
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
++iterations;
}}catch(Exception ex){
}
finally{
System.out.println("Debugging point D");
findNumber();
fixSolventAmount();
fixSoluteAmount();
}
You'll find "Debugging point D" above, this is printed a ton of times so it apparently is going after the recursion with a bunch of objects, and the rest of the code is screwed up because of this. I just need someone experienced to point out how this is flawed as one iteration of recursion.
If you need the entire class, I'll also copy / paste that bellow, but it's almost 200 lines... so yeah... (I know I shouldn't make classes that long but this object needed a lot of stuff in it).
import java.util.ArrayList;
public class InterpretInput {
/**
* #param remaining - The string that was input, what's left to analyze
*/
/** Variables */
private String remaining; //The string input by the user, containing what's left to analyze
private static int iterations = 0;
//Solvent Info
private double solventAmount; //The amount of the solvent expressed as final in MOLES
private M solventAmountMeas; //The measurement used in solventAmount
private double solventConc; //The concentration of the solvent
private M solventConcMeas; //The measurement used in solventConc
private E[] solventCompound; //The compound of the solvent
private E[] water = {E.H, E.H, E.O};
//Solute Info
private double soluteAmount; //The amount of solute in the solution
//Type of Data
private boolean isElement = false; //Determines if the information input is only an element
private boolean hasAmount = false; //Determines if the information input has an amount of solvent
private boolean isSolution = false; //determines if the information input is a solution
private int identificationNumber;
/** Constructor */
public InterpretInput (String remain){
remaining = remain;
}
/** Mutator Methods
* #throws Exception */
public void begin() throws Exception{
//Find Measurement
FindMeasurements measureObject = new FindMeasurements(remaining);
while (measureObject.exists() == true){
measureObject.determineNumber();
measureObject.determineMeasurement();
double solventAmountTemp = measureObject.getAmount();
M solventAmountMeasTemp = measureObject.getMeasurement();
if( (solventAmountMeasTemp.getType()) == 3 ){
isSolution = true;
solventConc = solventAmountTemp;
solventConcMeas = solventAmountMeasTemp;
}else{
hasAmount = true;
solventAmount = solventAmountTemp;
solventAmountMeas = solventAmountMeasTemp;
}
remaining = measureObject.getRemaining();
}
//Find Compound
FindCompound comp = new FindCompound(remaining);
comp.getCompound();
solventCompound = comp.getValue();
remaining = comp.getRemaining();
if (solventCompound.length == 1)
isElement = true;
//Find Solute
try{if(iterations == 0){
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
++iterations;
}}catch(Exception ex){
}
finally{
System.out.println("Debugging point D");
findNumber();
fixSolventAmount();
fixSoluteAmount();
}
}
public void fixSoluteAmount() throws Exception {
fixSolventAmount();
}
public void fixSolventAmount() throws Exception {
switch (identificationNumber){ //VIEW findNumber TO SEE INDEX OF THESE CASES
case 1:{
//In this situation, there would be nothing to change to begin with
break;
}
case 2:{
//In this situation, there would be nothing to change to begin with
break;
}
case 3:{
solventAmount *= solventAmountMeas.ofBase();
switch (solventAmountMeas.getType()){
case 1:{ //volume
if (!solventCompound.equals(water))
throw new Exception();
else{
solventAmount *= 1000; //Convert 1000g for every 1L
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
case 2:{ //mass
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
}
case 4:{
if(solventAmountMeas.equals(M.m)){
throw new Exception(); //I AM TAKING OUT THIS FEATURE, IT WILL BE TOO DIFFICULT TO IMPLEMENT
//BASICALLY, YOU CANNOT USE MOLALITY IN THIS PROGRAM ANYMORE
}
}
case 5:{
if(solventAmountMeas.equals(M.m))
throw new Exception(); //I AM TAKING OUT THIS FEATURE, IT WILL BE TOO DIFFICULT TO IMPLEMENT
//BASICALLY, YOU CANNOT USE MOLALITY IN THIS PROGRAM ANYMORE
double molarMass = 0;
for (E e : solventCompound)
molarMass += e.atomicMass();
solventAmount /= molarMass; //convert to moles
}
}
}
public void findNumber(){
/**
* 1 = Element
* 2 = Compound
* 3 = measured amount of compound
* 4 = specific concentration of solution
* 5 = Measured amount of specific concentration of solution
* */
if(isElement==true)
identificationNumber = 1;
else if(isSolution == false && hasAmount == false)
identificationNumber = 2;
else if(isSolution == false && hasAmount == true)
identificationNumber = 3;
else if(isSolution == true && hasAmount == false)
identificationNumber = 4;
else
identificationNumber = 5;
}
/** Accessory Methods */
public double getSolventAmount(){
return solventAmount;
}
public double getSoluteAmount(){
return soluteAmount;
}
public double getConcentration(){
return solventConc;
}
public E[] returnCompound(){
return solventCompound;
}
}
Your Begin function appears to call itself prior to incrementing the iterations variable. This will cause an infinite recursion. See my HERE notes in the code below.
//Find Solute
try{if(iterations == 0){
remaining = Whitespace.removePreceding(remaining);
String unused = remaining.substring(0);
InterpretInput solute = new InterpretInput(remaining);
// HERE - calls itself again, prior to incrementing
// iterations variable
solute.begin();
solute.fixSoluteAmount();
soluteAmount = solute.getSolventAmount();
isSolution = true;
// HERE - iterations is incremented, but too late
++iterations;
}}catch(Exception ex){
}
To resolve the recursion issue, you should increment iterations prior to the begin call.
The code here is pretty messy; it's a little difficult to figure out what the goal is. What are you trying to do with the string in InterpretInput, and why does it take such a complex solution (recursively built objects) as opposed to a loop or even just a recursive method?
Beyond that, however, it doesn't appear that there should be any way for your recursion to break. The only valid way for it to do so is if iterations != 0, which is never true because the ONLY time iterations is ever incremented is after the recursive call. Thus, I think the only reason the program terminates at all is that you overflow the stack, but the exception is caught by the empty catch block. Try printing something out in that block; I bet that's where the code is going even if you don't expect it to.
I have the following piece of code in Java implementing dynamic programming recursiverelatio:
public double routeCost() throws Exception {
double cost = Double.MAX_VALUE;
for (int l=i; l<=j; l++) {
if (! (customers.get(l) instanceof VehicleCustomer) )
continue;
double value = F(l,j) + (customers.get(l).distanceFrom(depot));
if (value < cost)
cost = value;
}
return cost;
}
private double F(int l, int m) {
//=========================== FIRST CASE ===========================
if (l==i && m==i) {
//System.out.println(i+","+j+","+l+","+m);
return firstCase();
}
//=========================== SECOND CASE ===========================
if (l==i && (i<m && m<=j) ) {
//System.out.println(i+","+j+","+l+","+m);
//analyses the possibility of performing all the soubtours based at heicle customert_i
return secondCase(i,m);
}
//=========================== GENERAL CASE ===========================
else {
System.out.println(i+","+j+","+l+","+m);
assert (customers.get(l) instanceof VehicleCustomer);
assert ( (i<l && l<=j) && (l<=m && m<=j) );
return Math.min(thirdCaseFirstTerm(l,m), thirdCaseSecondTerm(l,m));
}
}
private double firstCase() {
mainRoute.add(depot);
mainRoute.add(customers.get(i));
return depot.distanceFrom(customers.get(i));
}
private double secondCase(int i,int m) {
double caseValue = Double.MAX_VALUE;
int k = i;
while (k<m) {
double totalDemand=0;
for (int u=k+1; ( (u<=m) && (totalDemand<=truckCapacity) ); u++)
totalDemand += customers.get(u).getDemand();
double cost = F(i,k) + thita(i,k+1,m);
if (cost <= caseValue)
caseValue = cost;
k++;
}
return caseValue;
}
private double thirdCaseFirstTerm(int l, int m) {
double caseValue = Double.MAX_VALUE;
int k = i;
while (k<m) {
double totalDemand=0;
for (int u=k+1; ( (u<=m) && (totalDemand<=truckCapacity) ); u++)
totalDemand += customers.get(u).getDemand();
double cost = F(l,k) + thita(l,k+1,m);
if (cost <= caseValue)
caseValue = cost;
k++;
}
return caseValue;
}
private double thirdCaseSecondTerm(int l,int m) {
double caseValue = Double.MAX_VALUE;
int k = i;
for (Customer cust : customers) {
int h = customers.indexOf(cust);
if ( (!(cust instanceof VehicleCustomer)) || (h >=l)) {
continue;
}
double totalDemand=0;
for (int u=k+2; ( (u<=m) && (totalDemand<=truckCapacity) ); u++)
totalDemand += customers.get(u).getDemand();
double cost = F(h,k) + customers.get(h).distanceFrom(customers.get(l)) + thita(l,k+2,m);
if (cost < caseValue)
caseValue = cost;
}
return caseValue;
}
Method F(int,int) is invoked from the for loop in method routeCost().
I want to find a way to enforce that whenever the assertion assert (customers.get(l) instanceof VehicleCustomer);
` is not true, instead of going down to the return statement, I want to infrom the for loop from the routeCost() to continue to the next iteration. But F() has to return a value!
I know that what I'm trying to do violates almost every rule of object orientation, but I really need that.
You could throw an Exception in F() and catch it in routeCost().
This approach is much better than using assertions. They are rarely used in practice, and there's a good reason for this: exceptions are much more flexible and better suited for detecting errors, invalid input etc.
PS: When I say "rarely used", I base this statement on the fact that I saw hundreds of thousands of lines of Java code in the past years and I rarely came accross code that uses assertions.
You can return a special value like Double.NaN which you can check for with Double.isNaN(d)
You could make F() return a Double (instead of double) and return null in the case where your assert fails. Then have your outer for loop do a null check on the returned value before adding it, etc.
Why not replace the asserts with if statements? When the if-statements are true then calculate the value, otherwise return the MAX_VALUE of double. When F returns MAX_VALUE the cost will not be updated.
if (customers.get(l) instanceof VehicleCustomer) {
if ( (i<l && l<=j) && (l<=m && m<=j) ) {
return Math.min(thirdCaseFirstTerm(l,m), thirdCaseSecondTerm(l,m));
}
}
return Double.MAX_VALUE;
Use asserts during development to weed out things that should never happen in private methods. (Asserts can be switched off in production)
Throw an exception when something unexpected happens (e.g. a client of your class passes in invalid data).
However, from your question it seems you expect to get instances that are not VehicleCustomer, so asserts and exceptions are not the right approach here.
Peter Lawrey's and Jeff's answers will also work.