Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help please! You have been hired by a physics lab to write a program that w

ID: 3837425 • Letter: N

Question

                                                                                      Need help please!

You have been hired by a physics lab to write a program that will read in information from a text file and write specific results to a file.

Concepts

Arrays of Objects

Plain text file input/output

More practice writing supplier code to a specification


Input Data Files and storage

The physics lab that hired you has a set of 20 sensors that record color measurements. The information from these sensors is stored in a text file.

The text file is made up of 21 lines of data. The first line is the date of the readings in the form: mm/dd/yyyy. The next 20 lines are the data from the sensors, one sensor per line. Each line contains 5 pieces of information, all separated by spaces:

the sensor's name (1 token, no spaces)

3 integers representing the Red, Green, and Blue value of the color recorded by the sensor

an integer for the number of seconds this sensor recorded the color

You program does not have to be responsible for files that do not match this format (in other words, if the end user gives you a filename with bad data and the program crashes, that's ok). You can create any text file you want for testing (use a program like Notepad or any other basic text editor). Here are some files I've created for you to use: colors1.txt or colors2.txt

Make sure to look at and run the sample programs that illustrate reading data from a file.


Supplier Code Specification

Implement the two classes below, each in its own file. To get full credit, your program's public interface must match these descriptions exactly.

+ ColorSensor(String sensorName, Color c, int time) - initialize this object with the given values. Throws an IllegalArgumentException for invalid time (time must be > 0). Throws NullPointerException if either of the references are null.

+ Color getColor() -- returns the recorded Color of this ColorSensor

+ int getTime() -- returns the recorded seconds of this object

+ String getName() -- return the name of this ColorSensor

+ double getBrightness() -- returns the brightness of this ColorSensor's color. The formula for calculating brightness = sqrt( .241 R2 + .691 G2 + .068 B2 )

+ String toString() -- returns a String representation of this object, of the form "Name (r, g, b):s" Including this ColorSensor's name, the red, green, and blue values of the color, and the time.

+ void setColor(Color c) -- change the Color of this object. Throws a NullPointerException for a null argument.

+ void setSeconds(int s) -- change the recorded time for this object. Throws an IllegalArgumentException for invalid argument.

+ SensorArray(Scanner source) -- initializes a SensorArray object to hold ColorSensors, using the data from the Scanner. Note: this will crash if the file is not structured the correct way. That's fine.

+ String getDate() -- return the day of these readings

+ ColorSensor longest() -- returns the ColorSensor from this set with the longest recorded time.

+ int[] timeChange() -- returns an array of the absolute difference in time between each consecutive ColorSensor in this SensorArray. Specifically, the value at index 0 should be the aboslute time difference between the first ColorSensor and the second; the value at index 1 should be the absolute time difference between the second and third ColorSensor, etc

+ ColorSensor[] getClosest() -- returns an array containing two ColorSensor objects that had the closest brightness levels. This is between any two ColorSensors in the SensorArray, not necessarily consecutive.

+ void load(Scanner source) -- replaces the data in this SensorArray object, with the data from the Scanner. Any previous data is lost.

+ ColorSensor findSensor(String name) -- returns the ColorSensor object in this SensorArray with the given name. Returns null if that name is not in found.

+ String toString() -- returns a String that represents the state of this object. The String should contain the toString() for each ColorSensor objects, separated by a new line character.


User Interface

This program has a relatively simple user interface:

Brief user introduction

Prompt for 2 file names, one for input and one for output. Your program should not crash or end if the user gives you a filename that can't be read. Instead, the program should display a helpful error message and prompt for a new name.

Read the data from the input file.

To the output file, write on separate lines

the input file name

the date

the ColorSensor object with the longest time

each ColorSensor that have the closest brightness values.

To the user, display

the entire SensorArray, followed by

the time change results , one data per line.

Put the user interface into its own class, named SensorApp.

Suggestions

I hope by this point in the quarter you appreciate the benefit of working pieces of your solution one at a time. I recommend building and testing your ColorSensor class first. Next work on reading in the data (the SensorArray constructor method). Then tackle one or two methods at a time.

If it makes sense to decompose any of these methods, do so. However, the helper methods should all be private. Only these methods listed here should be part of the public interface.

Be aware of when a method needs to include the FileNotFoundException throws clause (unless you want to use try/catch blocks, but that is not a requirement for this assignment).


Documentation and Style

Make sure to write complete Javadoc comments for each class and each public method.

Include sufficient internal, algorithm documentation.

Use appropriate style (variable names, indenting, class constants, etc.) throughout the program.

Grading

/15 Program works and contains the proper methods. Good overall design.
/5 documentation, style

Here are some files I've created for you to use: colors1.txt or colors2.txt

colors1.txt                                                                                     

colors2.txt

class ColorSensor I leave this up to you to determine

+ ColorSensor(String sensorName, Color c, int time) - initialize this object with the given values. Throws an IllegalArgumentException for invalid time (time must be > 0). Throws NullPointerException if either of the references are null.

+ Color getColor() -- returns the recorded Color of this ColorSensor

+ int getTime() -- returns the recorded seconds of this object

+ String getName() -- return the name of this ColorSensor

+ double getBrightness() -- returns the brightness of this ColorSensor's color. The formula for calculating brightness = sqrt( .241 R2 + .691 G2 + .068 B2 )

+ String toString() -- returns a String representation of this object, of the form "Name (r, g, b):s" Including this ColorSensor's name, the red, green, and blue values of the color, and the time.

+ void setColor(Color c) -- change the Color of this object. Throws a NullPointerException for a null argument.

+ void setSeconds(int s) -- change the recorded time for this object. Throws an IllegalArgumentException for invalid argument.

Explanation / Answer

Here is the code for the question with comments. Please don't forget to rate the answer if it helped. Thank you very much.

ColorSensor.java

import java.awt.Color;

/**

* Class represent a sensor object

*/

public class ColorSensor {

  

   //member variabls for name , color and time

   protected String name;

   protected Color color;

   protected int time;

  

   /**

   * Constructor to initialize the sensor object with its name, color and time values

   * Throws NullPointerExcepion if sensor's name or color is null . Throws IllegalArgumentException if time is <=0.

   */

   public ColorSensor(String sensorName, Color c, int time)

   {

       if(sensorName == null)

           throw new NullPointerException("Sensor name can not be null");

       if(c == null)

           throw new NullPointerException("Color cannot be null");

       if(time<=0)

           throw new IllegalArgumentException("Time should be a +ve integer");

      

       this.name = sensorName;

       this.color = c;

       this.time = time;

   }

  

   /**

   *

   * @return the color object for this sensor

   */

   public Color getColor()

   {

       return color;

   }

  

   /**

   *

   * @return the time in seconds that this sensor measured the color

   */

   public int getTime()

   {

       return time;

   }

  

   /**

   *

   * @return the sensor's name

   */

   public String getName()

   {

       return name;

   }

  

   /**

   *

   *

   * @return the calculated brightness based on the RGB values in the color

   */

   public double getBrightness()

   {

       return Math.sqrt( 0.241 * color.getRed() + 0.691 * color.getGreen() + 0.068 * color.getBlue());

   }

  

   /**

   * returns a string representation of the sensor object in the format name (r,g,b):time

   */

   public String toString()

   {

       return name+" ("+color.getRed()+", "+color.getGreen()+","+color.getBlue()+") : "+time;

   }

  

   /**

   * Sets the color object for this sensor. Throws NullPointerException if c is null

   * @param c the color (for corresponding r,g,b) object to be set

   */

   public void setColor(Color c)

   {

       if(c == null)

           throw new NullPointerException("Color cannot be null");

       color = c;

   }

  

   /**

   * Sets the time measured by the sensor. Throws IllegalArgumentException if s is <=0

   *

   * @param s the actual time measured. Should be > 0

   */

   public void setSeconds(int s)

   {

       if(s<=0)

           throw new IllegalArgumentException("Seconds should be +ve integer");

       time = s;

   }

  

}

SensorArray.java

import java.awt.Color;
import java.lang.reflect.Array;
import java.time.chrono.MinguoDate;
import java.util.Arrays;
import java.util.Scanner;

/**
* Class representing a list of sensors and has functions to get some statistics about the sensors
*/
public class SensorArray {
  
   protected String date; //the date when the readings were taken
   protected ColorSensor sensors[]; //list of 20 sensors
  
   /**
   * Loads the 20 sensor objects from the file and also notes the date of the reading from input source
   * @param source the input source for loading the data
   */
   public SensorArray(Scanner source)
   {
       sensors = new ColorSensor[20]; //an array to hold 20 sensor objects
       load(source); //load the data into the objects
   }
  
   /**
   * Returns the date that was read from the input source
   * @return the date of readings as read from the input source
   */
   public String getDate()
   {
       return date;
      
   }
  
   /**
   * Returns the sensor with longest measuring time
   * @return the sensor with longest measuring time
   */
   public ColorSensor longest()
   {
       //find the max value of time in the entire array and return the object with max time
       int maxIdx=0;
       for(int i=1; i<sensors.length; i++)
           if( sensors[i].getTime() > sensors[maxIdx].getTime() )
               maxIdx = i;
       return sensors[maxIdx];
   }
  
   /**
   * Calculates the absolute difference in time values between consecutive sensors
   * @return an array of int representing absolute difference in measured times for consecutive sensors
   */
   public int[] timeChange()
   {
       int[] change = new int[sensors.length -1 ];
      
       for(int i=0; i<sensors.length-1; i++)
       {
           change[i] = Math.abs(sensors[i].getTime() - sensors[i+1].getTime());
       }
       return change;
   }
  
   /**
   * Sorts the input array of sensors based on the measured time using selection sort.
   * This method is used by getClosest() to sort a copy of the sensors array
   * @param arr - the array to be sorted
   * @return the sorted array
   */
   private ColorSensor[] sort(ColorSensor[] arr)
   {
       int minIdx=0;
       ColorSensor temp;
       for(int i=0; i<arr.length;i++)
       {
           minIdx = i;
           for(int j=i+1; j<arr.length; j++)
               if(arr[j].getTime() < arr[minIdx].getTime())
                   minIdx = j;
          
           if(minIdx != i)
           {
               temp = arr[i];
               arr[i] = arr[minIdx];
               arr[minIdx]= temp;
           }
              
       }
       return arr;
   }
   /**
   * Finds the 2 closest sensors. For this, a copy of the sensors array is sorted and then
   * diff between consecutive sensors is compared to the lowest difference measured so far.
   * Finally returns 2 sensors which have small absolute difference in times.
   * @return an array of size 2 with 2 closest sensors
   */
   public ColorSensor[] getClosest()
   {
       //first make a copy of the array and sort the copy of sensor objects
       ColorSensor[] sorted = sort(Arrays.copyOf(sensors, sensors.length));
      
       //get the difference between first 2 elements
       int diff = Math.abs(sorted[0].getTime() - sorted[1].getTime());
       int closestIdx=0;
      
      
       for(int i=1; i<sorted.length-1; i++)
       {
           //whenever the current differnce is less than the saved minimum difference, update it
           if(Math.abs(sorted[i].getTime()-sorted[i+1].getTime()) < diff )
           {
               closestIdx = i;
               diff = Math.abs(sorted[i].getTime()-sorted[i+1].getTime());
           }
       }
      
       //create an array for the 2 closest sensors and return it
       ColorSensor closest[]=new ColorSensor[2];
       closest[0] = sorted[closestIdx];
       closest[1] = sorted[closestIdx+1];
      
       return closest;
   }

   /**
   * Loads the data from source and populates the sensor objects
   * @param source the source from where to fetch data
   */
   public void load(Scanner source)
   {
       date = source.next();
      
       String name;
       int r,g, b, time;
       for(int i=0;i<sensors.length;i++)
       {
           name = source.next();
           r = source.nextInt();
           g = source.nextInt();
           b = source.nextInt();
           time = source.nextInt();
           sensors[i] = new ColorSensor(name, new Color(r,g,b), time);
       }
         
       source.close();
   }
  
   /**
   * returns sensor for the given name
   * @param name the name of sensor to search for
   * @return the sensor for the given name if found, null if not found.
   */
   public ColorSensor findSensor(String name)
   {
       for(int i=0; i<sensors.length; i++)
       {
           if(sensors[i].getName().equals(name))
               return sensors[i];
       }
       return null;
   }
   /**
   * String representation of all the sensor objects in the array
   */
   public String toString()
   {
       String str ="";
       for(int i=0; i<sensors.length; i++)
       {
           str += sensors[i].toString()+ " ";
       }
      
       return str;
   }
}

SensorApp.java

import java.io.File;

import java.io.FileNotFoundException;

import java.io.PrintWriter;

import java.util.Scanner;

public class SensorApp {

   public static void main(String[] args) {

       Scanner keyboard = new Scanner(System.in);

       Scanner source;

       PrintWriter outFile;

       String inputFilename, outputFilename;

      

       //keep prompting user to enter a valid filename for input until a valid filename is given

       do

       {

           System.out.print(" Enter input filename: ");

           inputFilename = keyboard.nextLine().trim();

           try {

               source = new Scanner(new File(inputFilename));

               break;

           } catch (FileNotFoundException e) {

               System.out.println("Cannot open input file "+inputFilename+". Please try another file.");

           }

          

       }while(true);

      

      

       System.out.print(" Enter output filename: ");

       outputFilename = keyboard.nextLine().trim();

       try {

           outFile = new PrintWriter(new File(outputFilename));

       } catch (FileNotFoundException e) {

           System.out.println("Error occured while creating output file");

           return;

       }

      

       SensorArray sensors = new SensorArray(source);

       outFile.write("Input filename : "+inputFilename+" ");

       outFile.write("Date: "+sensors.getDate()+" ");

       outFile.write("Longest time sensor: "+sensors.longest()+" ");

      

       ColorSensor closest[] = sensors.getClosest();

       outFile.write("Closest sensors: "+closest[0] +" "+closest[1]);

       outFile.close();

      

       //display the sensor and time change data to user

       System.out.println("The sensor data is as follows: "+sensors.toString());

      

       int diff[] = sensors.timeChange();

       System.out.println("The time change array is as follows:");

       for(int i=0; i<diff.length;i++)

           System.out.println("t["+i+"] = "+diff[i]);

      

   }

}

sample output for colors1.txt

Enter input filename: colors1.txt

Enter output filename: out1.txt

The sensor data is as follows:

sensor1 (238, 172,53) : 76

sensor2 (137, 62,6) : 23

sensor3 (107, 147,188) : 89

sensor4 (15, 86,240) : 103

sensor5 (29, 230,161) : 23

sensor6 (224, 53,211) : 94

sensor7 (139, 178,24) : 6

sensor8 (23, 46,159) : 55

sensor9 (69, 35,194) : 103

sensor10 (77, 234,234) : 101

sensor11 (232, 116,60) : 13

sensor12 (170, 199,231) : 43

sensor13 (207, 77,189) : 49

sensor14 (196, 79,202) : 83

sensor15 (161, 111,148) : 47

sensor16 (149, 152,222) : 106

sensor17 (138, 255,154) : 61

sensor18 (176, 94,183) : 98

sensor19 (3, 83,8) : 79

sensor20 (0, 236,193) : 53

The time change array is as follows:

t[0] = 53

t[1] = 66

t[2] = 14

t[3] = 80

t[4] = 71

t[5] = 88

t[6] = 49

t[7] = 48

t[8] = 2

t[9] = 88

t[10] = 30

t[11] = 6

t[12] = 34

t[13] = 36

t[14] = 59

t[15] = 45

t[16] = 37

t[17] = 19

t[18] = 26

output file out1.txt

Input filename : colors1.txt

Date: 10/30/2015

Longest time sensor: sensor16 (149, 152,222) : 106

Closest sensors: sensor5 (29, 230,161) : 23   sensor2 (137, 62,6) : 23

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote