Tuesday, January 28, 2014

Java - if and if-else

import java.util.Random;

public class Test {
final static int LOOP_COUNT = 10000;
static String dummyData;

public static void main(String[] args) {

long startTime = System.nanoTime();

ifWithElse();

long endTime = System.nanoTime();
double elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);

startTime = System.nanoTime();

onlyIf();

endTime = System.nanoTime();
elaspedTime = (endTime - startTime) / 1000000.0;

System.out.println(elaspedTime);
}

static void onlyIf() {
Random random = new Random();
String result = null;
int data = 1000 + random.nextInt();

for (int i = 0; i < LOOP_COUNT; i++) {
if (data < 50) {
result = "50";
}
if (data < 150) {
result = "150";
}
if (data < 250) {
result = "250";
}
if (data < 350) {
result = "350";
}
if (data < 450) {
result = "450";
}
if (data < 550) {
result = "550";
}
if (data < 650) {
result = "650";
}
if (data < 750) {
result = "750";
}
if (data < 850) {
result = "850";
}
if (data < 950) {
result = "950";
}
if (data >= 950) {
result = "over";
}

resultProcess(result);
}
}

static void ifWithElse() {
Random random = new Random();
String result = null;
int data = 1000 + random.nextInt();

for (int i = 0; i < LOOP_COUNT; i++) {
if (data < 50) {
result = "50";
} else if (data < 150) {
result = "150";
} else if (data < 250) {
result = "250";
} else if (data < 350) {
result = "350";
} else if (data < 450) {
result = "450";
} else if (data < 550) {
result = "550";
} else if (data < 650) {
result = "650";
} else if (data < 750) {
result = "750";
} else if (data < 850) {
result = "850";
} else if (data < 950) {
result = "950";
} else {
result = "over";
}

resultProcess(result);
}
}

public static void resultProcess(String result) {
dummyData = result;
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.