In: Computer Science
Java guessing game:
For this program you will use Linear Search.
- Ask the user to choose between a number from 0 to 2000.
- The user will guess how long the linear search will take in nanoseconds,
- After the user puts in their answer, show the user the difference between the actual answer and their answer.
(Example: The user puts in 5 nanoseconds. The actual time is 11 nanoseconds. The program will show 6 nanoseconds.)
There should be a class for the program to do the Linear Search and a separate tester class for the user questions and answers.
LinearSearch.java:
Raw_code:
// LinearSearch class
public class LinearSearch{
int number = 0;
// constructor which takes number as parameter
LinearSearch(int number){
this.number = number;
}
// start method which takes user guess time as parameter
long start(long time){
// intializing start time by calling nanoTime method of System
class
long startTime = System.nanoTime();
// for loop for Search the number from 0 until the number is
reached
for(int num = 0; num <= number; num++);
// intializing the end time
long endTime = System.nanoTime();
// caulating the timeduration by substracting the startTime from
endTime
long timeduration = endTime - startTime;
// returning the difference b/2 the timeduration and time
return timeduration - time;
}
}
Driver.java:
Raw_code:
import java.util.Scanner;
public class Driver{
// main method
public static void main(String[] args){
int number;
long time;
// taking the number form user and storing in number variable
Scanner input = new Scanner(System.in);
System.out.print("Enter a number between 0 and 2000: ");
number = input.nextInt();
// creating Linear Search object on the number
LinearSearch ls = new LinearSearch(number);
// taking the time from user and storing in time variable
System.out.print("How laong the Linear Search will take in
nanoseconds: ");
time = input.nextLong();
// calling the start method of LinearSearch object with user time
as argument
// and printing the return value
System.out.println("The time difference is: " +
ls.start(time));
}
}