Question 1. Digital sounds can be represented as an array of integer values. For this question, you will write two unrelated methods of the Sound class.
public class Sound
{
/** the array of values in this sound; guaranteed not to be null */
private int[] samples;
/** Changes those values in this sound that have an amplitude
* greater than limit */
* Values greater than limit are changed to limit.
* @param limit the amplitude limit
* Precondition: limit >= 0
* @return the number of values in this sound that this
* method changed
*/
public int limitAmplitude(int limit)
{ /* to be implemented in part (a) */ }
/** Removes all silence from the beginning of this sound.
* Silence is represented by a value of 0.
* Precondition: samples contains at least one nonzero value
* Postcondition: the length of samples reflects the removal
* of starting silence
*/
public void trimSilenceFromBeginning()
{ /* to be implemented in part (b) */ }
// There may be instance variables, constructors, and methods
// that are not shown.
}
Part a. The volume of a sound depends on the amplitude of each value in the sound. The amplitude of a value is its absolute value. For example, the amplitude of -2300 is 2300 and the amplitude of 4000 is 4000.
Write the method limitAmplitude that will change any value that has an amplitude greater than the given limit. Values that are greater than limit are replaced with limit, and values that are less than -limit are replaced with βlimit. The method returns the total number of values that were changed in the array. For example, assume that the array samples has been initialized with the following values.
If the current value is less than the negative of the limit, then it should be reset to the negative of the limit and the count of values should be incremented.
You could use a while loop, but if you are looping through all values in an array it is better to use a for loop. It is easier to make mistakes with a while loop and forget to increment a value in the body of the loop so that the loop eventually stops.
The method limitAmplitude below contains the correct code for a solution to this problem, but the code blocks are mixed up. Drag the blocks from the left to the right and put them in order so that the code would work correctly.
public int limitAmplitude(int limit)
{
---
int numChanged = 0;
for (int i = 0; i < samples.length; i++)
{
---
if (samples[i] > limit)
{
---
samples[i] = limit;
numChanged++;
---
} // end first if
if (samples[i] < -limit)
{
---
samples[i] = -limit;
numChanged++;
---
} // end second if
---
} // end for
---
return numChanged;
---
} // end method
FRQ Sound A: Write the method limitAmplitude that will change any value that has an amplitude greater than the given limit. Values that are greater than limit are replaced with limit, and values that are less than -limit are replaced with βlimit. The method returns the total number of values that were changed in the array. The main method has code to test your solution.