Important Notice:

Practice-It will be discontinued as of November 1st, 2024. After this date, the website will remain online for a transitional period, but login will be restricted to University of Washington NetID authentication. This marks the next phase towards the platform's full retirement. Thank you for your use and support of the application over the years.

If you are looking for an alternative, a similar tool, CodeStepByStep, was developed independently by the original author of Practice-It, and is available at codestepbystep.com**

logo Practice-It logo

BJP3 Exercise 7.12: priceIsRight

Language/Type: Java arrays
Author: Roy McElmurry (on 2013/04/01)

Write a method priceIsRight that accepts an array of integers bids and an integer price as parameters. The method returns the element in the bids array that is closest in value to price without being larger than price. For example, if bids stores the elements {200, 300, 250, 999, 40}, then priceIsRight(bids, 280) should return 250, since 250 is the bid closest to 280 without going over 280. If all bids are larger than price, then your method should return -1.

The following table shows some calls to your method and their expected results:

Arrays Returned Value
int[] a1 = {900, 885, 989, 1}; priceIsRight(a1, 800) returns 1
int[] a2 = {200}; priceIsRight(a2, 120) returns -1
int[] a3 = {500, 300, 241, 99, 501}; priceIsRight(a3, 50) returns -1

You may assume there is at least 1 element in the array, and you may assume that the price and the values in bids will all be greater than or equal to 1. Do not modify the contents of the array passed to your method as a parameter.

Type your solution here:


This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

You must log in before you can solve this problem.


Log In

If you do not understand how to solve a problem or why your solution doesn't work, please contact your TA or instructor.
If something seems wrong with the site (errors, slow performance, incorrect problems/tests, etc.), please

Is there a problem? Contact a site administrator.