The code:
public class Branches {
public double justOneIf(int a) {
double result;
if (a > 0) {
result = 1.0d;
} else {
result = -1.0d;
}
return result;
}
public String switches(int x) {
String result;
switch (x) {
case 0: {
result = "zero";
break;
}
case 1: {
result = "one";
break;
}
case 2: {
result = "two";
break;
}
default: {
result = "kill all humans";
}
}
return result;
}
public int deepIf(int x) {
int y;
if (x == 0) {
y = 1;
} else {
if (x > 0) {
y = 2;
} else {
y = 3;
}
}
return y;
}
}
In OpenClover (version 4.4.1) report I got metrics for this class:
Code metrics
Branches:6
...
Why six branches here? How does clover count it?
I've got it. It's pretty simple: one "IF" means 2 branches. Just it.
Branch coverage
Branch coverage (or 'decision coverage') is a code coverage metric
that measures which possible branches in flow control structures are
followed. Clover does this by recording if the boolean expression in
the control structure evaluated to both true and false during
execution.
Related
When iterate() is first called i'm generating a random number between 1-1024 and then checking if that random number is equal to 1. If it is, then done = true and the return value should be 10. If it's not, then the value of x should be decremented (x now = 9). I then expect getRandNum() to be called again within iterate(), this time generating a random number between 1-512 and checking if it's equal to 1 etc, etc... until the return value for x can only be equal to 1.
import java.util.Random;
public class Main {
static boolean done = false;
public static int rand(int x) {
Random rand = new Random();
return rand.nextInt(x) + 1;
}
public static int value(int x) {
return (int) Math.pow(2, x);
}
public static int getRandNum(int x) {
return rand(value(x));
}
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (done = false);
return x;
}
public static void main(String[] args) {
System.out.println(iterate());
}
}
Right now iterate() only returns 9. I need it to return anything from 1-10. There's clearly a logical error, but i can't see it.
Small error: you did while(done = false). This assigns done to false. The correct way to do this is while(!done).
public static int iterate() {
int x = 10;
do {
if (getRandNum(x) == 1) {
done = true;
}
else {
if (x > 1) {
x--;
}
else {
x = 1;
done = true;
}
}
} while (!done);
return x;
}
If you do this it prints 1.
I have the following problem: Having a boolean static method that computes similarity between two integers, I am asked to return 4 results:
without changing the return type of the method, it
should stay boolean.
without updating/using the values of external variables and objects
This is what I've done so far (I can't change return value from boolean to something else, such as an int, I must only use boolean):
public static boolean isSimilar(int a, int b) {
int abs=Math.abs(a-b);
if (abs==0) {
return true;
} else if (abs>10) {
return false;
} else if (abs<=5){
//MUST return something else, ie. semi-true
} else {
//MUST return something else, ie. semi-false
}
}
The following is bad practice anyway, but If you can try-catch exceptions you can actually define some extra outputs by convention. For instance:
public static boolean isSimilar(int a, int b) {
int abs = Math.abs(a-b);
if (abs == 0) {
return true;
} else if (abs > 10) {
return false;
} else if (abs <= 5){
int c = a/0; //ArithmeticException: / by zero (your semi-true)
return true;
} else {
Integer d = null;
d.intValue(); //NullPointer Exception (your semi-false)
return false;
}
}
A boolean can have two values (true or false). Period. So if you can't change the return type or any variables outside (which would be bad practice anyway), it's not possible to do what you want.
Does adding a parameter to the function violate rule 2? If not, this might be a possible solution:
public static boolean isSimilar(int a, int b, int condition) {
int abs = Math.abs(a - b);
switch (condition) {
case 1:
if (abs == 0) {
return true; // true
}
case 2:
if (abs > 10) {
return true; // false
}
case 3:
if (abs <= 5 && abs != 0) {
return true; // semi-true
}
case 4:
if (abs > 5 && abs <= 10) {
return true; // semi-false
}
default:
return false;
}
}
By calling the function 4 times (using condition = 1, 2, 3 and 4), we can check for the 4 results (only one would return true, other 3 would return false).
I am quite new to Java and I am making a string parsing calculator. I have a piece of code which has some almost identical fragments which I would like being extracted into some method or so, but I could not come up with an idea how to do it.
Here is a piece of code:
case '+':
current_priority = 1;
if (last_priority < current_priority) {
i++;
first_operand = new Add(first_operand, parse(expression, current_priority));
} else {
i--;
return first_operand;
}
break;
case '*':
current_priority = 2;
if (last_priority < current_priority) {
i++;
first_operand = new Multiply(first_operand, parse(expression, current_priority));
} else {
i--;
return first_operand;
}
break;
case '/':
current_priority = 2;
if (last_priority < current_priority) {
i++;
first_operand = new Divide(first_operand, parse(expression, current_priority));
} else {
i--;
return first_operand;
}
break;
I would like to get a method or something which would copy the behavior of the following fragment:
current_priority = x;
if (last_priority < current_priority) {
i++;
first_operand = new Something(first_operand, parse(expression, current_priority));
} else {
i--;
return first_operand;
}
The problem is that as far as I'm concerned I can't declare non-initialized objects in Java and for my program it's important not to run the constructor of Something (Add/Multiply/Divide) before making sure it's really needed, so passing an object to this method is not a way, I have to somehow create an object inside this method, but this seems to lead to making two switches with identical cases and I would like more elegant solution if possible. I also don't know how to reproduce the return/assignment behavior depending of a condition inside a method. I would really appreciate any help.
A Use a Factory
current_priority = x;
if (last_priority < current_priority) {
i++;
first_operand = myOperationFactory.createOperand(operation, first_operand, parse(expression, current_priority));
} else {
i--;
return first_operand;
}
public class OperationFactory {
public Operand createOperand(char operation, Operand firstOperand, Operand secondOperand) {
switch (operation) {
case '+': return new Add(firstOperand, secondOperand);
case ...
}
B (advanced) use enum and reflection.
public enum Operations {
ADD('+', Add.class),
MULTIPLY('*', Multiply.class)
...;
private char symbol;
private Constructor<? extends Operation> constructor;
public Operations(char symbol, Class<? extends Operation> clazz) {
this.symbol = symbol;
this.constructor= clazz.getConstructor(Operand.class, Operand.class);
}
public Operation create(Operand operan1, Operand operand2) {
return constructor.newInstance(operand1, operand2);
}
public char getSymbol() {
return this.symbol;
}
public static Operations getFromSymbol(char symbol) {
for (Operations op : Operations.values()) {
if (op.getSymbol() == symbol) {
return op;
}
}
}
}
and
current_priority = x;
if (last_priority < current_priority) {
i++;
Operations operation = Operations.fromSymbol(opSymbol);
first_operand = operation.create(first_operand, parse(expression, current_priority));
....
I beginner in Java and I ask tell me some words about Java tradition of writing generic code. I wrote helper class for pushing items into generic sorted collections in code below and I want to know it is accepted? Or I should extends some base class of collections? Or other ways to welcome more in Java?
package com.rkovalev.Helper;
import java.util.Comparator;
import java.util.List;
public abstract class ListExtensions {
public static <T> void addOnCompare(List<T> collection, T item, Comparator<T> comparator) {
synchronized(collection) {
int i = 0;
int size = collection.size();
if (size == 1) {
int diff = comparator.compare(item, collection.get(0));
switch(diff) {
case 1: i++; break;
default: break;
}
} else {
int range = size - 1;
i = size / 2;
int left = 0;
int right = range;
while(true) {
if (i <= 0) { i = 0; break; }
if (i > range) { i = range; break; }
int diff = comparator.compare(item, collection.get(i));
if (diff == 0) break;
else {
if (diff == -1) right = i;
if (diff == 1) left = i;
int near = i + diff;
if (near < 0) { i = 0; break; }
if (near > range) { i = range + 1; break; }
int diff_near = comparator.compare(item, collection.get(near));
if (diff_near == 0) { i = diff_near; break; }
if (diff_near == diff) {
int step = (right-left)/2;
if (step == 0) step = 1;
switch(diff){
case -1:
right = i;
i = i - step; break;
case 1:
left = i;
i = i + step; break;
}
} else if (diff > diff_near) {
i = near; break;
} else { break; }
}
}
}
collection.add(i, item);
}
}
}
If you want to make extra "generic" functionality available for all collection classes, then writing the functionality as a static method in a "helper" class is the right way to go.
Adding the method to a base class of the existing collection classes would not work. It would entail modifying the standard Java class library, and nobody in their right mind would do that. (It is technically possible, but you would be creating a portability nightmare for your code. Not to mention legal issues if you used the trademarked term "Java" in connection with your code.)
I have several cases and I am just using simple if ... if else blocks.
How can I reduce the number of if statements in this code?
Perhaps I could use a lookup table, but I am not sure how to implement it in Java.
private int transition(char current, int state)
{
if(state == 0)
{
if(current == 'b')
{
return 1;
}
else
return 0;
}
if(state == 1)
{
if(current == 'a')
{
return 2;
}
else
return 0;
}
if(state == 2)
{
if(current == 's')
{
return 3;
}
else
return 0;
}
if(state == 3)
{
if(current == 'e')
{
return 3;
}
if(current == 'b')
{
return 4;
}
else
return 0;
}
if(state == 4)
{
if(current == 'a')
{
return 5;
}
else
return 0;
}
if(state == 5)
{
if(current == 'l')
{
return 6;
}
else
return 0;
}
else
return 0;
}
What you're trying to do looks very much like a finite state machine, and these are usually implemented with the help of a transition table. Once you set up the table, it's simply a matter of indexing to the position you want to get the return value. Assuming your return values are all less than 256, you can use a 2D byte array:
byte table[][] = new byte[NUM_STATES][NUM_CHARACTERS];
// Populate the non-zero entries of the table
table[0]['b'] = 1;
table[1]['a'] = 2;
// etc...
private int transition(char current, int state) {
return table[state][current];
}
Well, you can easily utilize hash. Simple and clean.
// declare hashtable
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("0-b", 1);
map.put("1-a", 2);
map.put("2-s", 3);
...
// get result
Integer result = map.get(state + "-" + current);
// change null (nothing found) to zero
return result == null ? 0 : result;
consider interfaces + enums:
interface State<T>
{
public void State<T> step(T input);
}
enum MyState implements State<Character> {
STATE0(0) { #Override public void MyState step(Character c) { return c == 'b' ? STATE1 : STATE0; }},
STATE1(1) { #Override public void MyState step(Character c) { return c == 'a' ? STATE2 : STATE0; }},
/* rest of states here */
final private int value;
MyState(int value) { this.value = value; }
public int getValue() { return this.value; }
}
class SomeClass
{
public MyState currentState = STATE0;
public void step(char input)
{
this.currentState = this.currentState.step(input);
}
}
i switch statement would be best here:
private int transition(char current, int state)
{
switch(state)
{
case 0:
return current == 'b' ? 1 : 0;
case 1:
return current == 'a' ? 2 : 0;
case 2:
return current == 's' ? 3 : 0;
case 3:
return current == 'e' ? 3 : (current == 'b' ? 4 : 0);
case 4:
return current == 'a' ? 5 : 0;
case 5:
return current == 'l' ? 6 : 0;
default:
return 0;
}
}
And a note, theres only 5 if statements there checking pure intergers, this is not exactly an overhead.
Looks like you need a better abstraction for a finite state machine. Think about a class that encapsulates what you want in a better way so you can extend it by configuration rather than modifying code.
If this code is about to be expanded over the time, why not use a state machine? Each state will return the next state based on the character it receives. Maybe it's an overkill for this code, but it'll be a lot easier to maintain, expand & read.
Use switch statement for the outer if chain:
switch (state) {
case 0: <code> ; break;
case 1: <code> ; break;
case 2: <code> ; break;
<etc>
default: return 0; break;
}