Question: When you execute the CompareLoopTimes program shown in Figure 6-29, you will occasionally see a negative number output when the nanoseconds values retrieved fall in

When you execute the CompareLoopTimes program shown in Figure 6-29, you will occasionally see a negative number output when the nanoseconds values retrieved fall in different seconds. Modify the program to fix this problem, and save the file as CompareLoopTim:es3.java. (Hint: It might take hundreds or thousands of executions for you to "catch" the program near the end of a second in order to test your modifications. For testing purposes, you can assign values to the start and stop times instead of retrieving them from the LocalDateTime class.)

a. Write an application that counts by three from 3 through 300 inclusive, and that starts a new line after every multiple of 30 (30, 60, 90, and so on). Save the file as CountByThrees.java.

b. Modify the CountByThrees application so that the user enters the value to count by. Start each new line after 10 values have been displayed. Save the file as CountByAnything.java.

Figure 6-29:

import java.time.*;

public class CompareLoopTimes

{

public static void main(String[] args)

{

int startTime, endTime;

final int REPEAT = 100000;

final int FACTOR = 1000000;

LocalDateTime now;

now = LocalDateTime.now();

startTime = now.getNano();

for (int x = 0; x <= REPEAT; ++x);

for(int y = 0; y <= REPEAT; ++y);

now = LocalDateTime.now();

endTime = now.getNano();

System.out.println("Time for loops starting from 0: " +

((endTime - startTime) / FACTOR) + " miliseconds");

now = LocalDateTime.now();

startTime = now.getNano();

for(int x = REPEAT; x >= 0; --x )

for(int y = REPEAT; y >= 0; --y);

now = LocalDateTime.now();

endTime = now.getNano();

System.out.println("Time for loops ending with 0: " +

((endTime - startTime) / FACTOR) + " miliseconds");

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!