How about:
public abstract void solve();
public void solveProblem() {
startTime();
solve();
endTime();
System.out.println(timeTaken);
}
Then just override solve and call solveProblem.
Question
It has been a while since I've programmed in Java and I just can't seem to solve it so I apologize in advance for anything stupid I might have done.
I am currently solving a list of math problems in Java. I create a new class called ProblemX for every problem. I want each class to print the duration time of the execution. Rather than programming this in each seperate class I though I'd use some inheritance but that's where I got stuck.
Public abstract class Problem{
public static void main(String[]args){
Problem p = new Problem();
long startTime = System.nanoTime();
p.solve();
long endTime = System.nanoTime();
System.out.println("Execution time: " + (endTime - startTime) + " nanoseconds");
}
abstract void solve();
}
This doesn't work because I can't create an instance of Problem in an abstract class. I can't use a Solveable interface because then Problem has to define 'solve'.
Obviously I'm missing something here so if anyone could help it would be greatly appreciated.
Solution
How about:
public abstract void solve();
public void solveProblem() {
startTime();
solve();
endTime();
System.out.println(timeTaken);
}
Then just override solve and call solveProblem.
OTHER TIPS
You can do something like
public abstract class Problem{
long startTime;
long endTime;
public void startTime(){
startTime = System.nanoTime();
}
public void endTime(){
endTime = System.nanoTime();
}
public long measure(){
return endTime - startTime;
}
}
public class ProblemX extends Problem{
public static void main(String[] a){
ProblemX x = new ProblemX();
x.startTime();
//do your work
x.endTime();
System.out.println("time taken" + x.measure());
}
}
Something like this perhaps?
package com.stackoverflow;
public abstract class Problem {
public static void main(String[] args) {
Problem p = new Problem(){
@java.lang.Override
protected void doCalculation() {
for (int i = 0; i < 1000; i++) {
System.out.println("Printing number... " + i);
}
}
};
p.solve();
System.out.println("Execution time: " + p.getElapsedTime() + " nanoseconds");
}
private long startTime, endTime;
private void doStartTime() {
startTime = getSystemNanoTime();
}
private void doEndTime() {
endTime = getSystemNanoTime();
}
private long getSystemNanoTime() {
return System.nanoTime();
}
protected abstract void doCalculation();
public void solve() {
doStartTime();
doCalculation();
doEndTime();
}
public long getElapsedTime() {
return endTime - startTime;
}
}
lets say that you have a ProblemX class which overrides Problem. you should change the following rows in the static main method:
from:
Problem p = new Problem(){
@java.lang.Override
protected void doCalculation() {
for (int i = 0; i < 1000; i++) {
System.out.println("Printing number... " + i);
}
}
};
to:
Problem p = new XProblem();