In: Computer Science
How is this method coded in java?
int differential(int[] post)
differential computes the virtual differential for a single post record and returns the differential. The differential is simply the difference between ups and downs. differential is virtual because it is not stored in a post record.
/// Compute the differential between "ups" (at index 1) and "downs"
/// (at index 2). The differential is not maintained in the data but is a
/// virtual field derived by the calculation performed here
public static int differential(int[] post) {
// TODO : Implement Here
return 0;
}
Post data:
0001 505361 236677
0002 629710 727941
0003 414780 842861
0004 702957 401854
0005 862865 315572
0006 930013 609421
0007 326101 220500
0008 732457 404837
0009 878259 411163
0010 227645 638470
One of the thing you failed to metion that from where these values are coming. I want to ask that if we are reading these values from a file or they are simply stored in the code.
Here I am providing the solution by simply assuming that we are reading thses values from a file.
Also please not that save the text file in same folder where is your java code.
Working: We simply raead each line from a file and pass to the method as an array where it calculates the differential and return in int which will we print on console.
----------------------------------------------------------------------------------------------------------------
Code:
import java.util.*;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
class Main
{
//method to calculate virtual differential
public static int differential(int[] post) {
//return the difference of ups (at index 1) to downs (at index
2)
return post[1] - post[2];
}
//execution of program starts from here
public static void main(String[] args)
{
String fileName = "data.txt" ;
//save this file in same folder where your java file is
stored.
try
{
Path path =
Paths.get(fileName);
Scanner scanner
= new Scanner(path);
System.out.println("Reading all tweets from file:\n");
//read each
number line by line
while(scanner.hasNextLine()){
//create an array
int arr[] = new int[3];
//tweet number
arr[0] = Integer.parseInt(scanner.next());
arr[1] = Integer.parseInt(scanner.next());
//ups
arr[2]= Integer.parseInt(scanner.next());
//downs
//pass these values to method as an array
int count = differential(arr);
//print the result
System.out.println("Tweet Num: " + arr[0] + "
Virtual Differential: " + count);
}
scanner.close();
}
catch(Exception e)
{
System.out.println("Unable to read file");
}
}
}
----------------------------------------------------------------------------------------
Output: