Basically I have a Boolean that I want to be true only if it equals one of the bad numbers in my fruit array. Here's what I'm trying to do:
The following is pseudocode:
public class fruitTypes {
public static int[] fruit = new int[10];
fruit[1], fruit[4], fruit[7] = rotten_fruit_numbers.
}
public class any_bad_fruit {
currentFruit = my_current_fruit;//loops through fruits i have
boolean has_bad_fruit = currentFruit == rotten_fruit_numbers;
//this, i want to return true because some of the numbers are bad fruits.
}
The reason I'm trying this is because I'm trying to have an array of some sort of numbers in my static class. I may be better off with an enum, but is this logical and/or possible?
I am not sure, what you exactly want, but try this(you can change arrays content):
public static void main(String[] args){
int[] fruit = {1,2,3,4,5,6,7,8,9};
int[] rotten = {17,3,23};
System.out.println(isRotten(fruit,rotten)); // prints false or true, if array contains rotten ints
}
public static boolean isRotten(int[] fruit, int[] rotten){
for(int part : fruit){
for(int rottenPart : rotten){
if(part == rottenPart) return true;
}
}
return false;
}
I believe the question you are asking is "how can I create a function that determines whether any elements in a given array of integers is in another array of integers".
Here is an example of a solution:
private final int[] rottenFruit = {3, 7, 11}; // must be sorted
public boolean containsRottenFruit(int[] fruitArray) {
return Arrays.stream(fruitArray)
.anyMatch(fruit -> Arrays.binarySearch(rottenFruit, fruit) >= 0);
}
This uses Java 8 streams. An equivalent solution for previous versions would be:
public boolean containsRottenFruit(int[] fruitArray) {
for (int fruit: fruitArray) {
if (Arrays.binarySearch(rottenFruit, fruit) >= 0) {
return true;
}
}
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.