129,537 views
10 votes
10 votes
This is JAVA

A local grocery store has asked you to design a method to verify if their produce is okay to put on the shelves. The method takes an array of ints which represent the ages of various produce items. If an item is less than 4 days old, or more than 24, it should not be put on the shelves, and the method should return false. Otherwise, it should return true.
Examples:
verifyProduce({5,7,14,20,24}) -> true
verifyProduce({16,3,12,13}) -> false
verifyProduce({14,20,23,26}) -> false
1
public boolean verifyProduce(int[] ages) {
2
3
}

User Zelf
by
2.7k points

1 Answer

16 votes
16 votes
To implement the method described in the question, you could use the following code:

public boolean verifyProduce(int[] ages) {
for (int age : ages) {
if (age < 4 || age > 24) {
return false;
}
}
return true;
}
This code iterates over each element in the ages array and checks if its value is less than 4 or greater than 24. If any of the ages meet this condition, the method returns false immediately. Otherwise, the method returns true after all elements in the array have been checked.

Here is an example of how this method might be used in a Java program:

public class Main {
public static void main(String[] args) {
int[] ages1 = {5, 7, 14, 20, 24};
int[] ages2 = {16, 3, 12, 13};
int[] ages3 = {14, 20, 23, 26};

System.out.println(verifyProduce(ages1)); // outputs: true
System.out.println(verifyProduce(ages2)); // outputs: false
System.out.println(verifyProduce(ages3)); // outputs: false
}

public static boolean verifyProduce(int[] ages) {
User Eisbaw
by
3.0k points