This assignment will give you practice with arrays. Submit the two java files(Pa
ID: 3529093 • Letter: T
Question
This assignment will give you practice with arrays. Submit the two java files(Parity.java and Even.java).
? Write a static method called hasAlternatingParity that returns whether or not an array of
integers has alternating parity (true if it does, false otherwise). The parity of an integer is 0
for even numbers and 1 for odd numbers. To have alternating parity, a list would have to
alternate between even and odd numbers, as in the following list:
(3, 2, 19, 8, 43, 64, 1, 0, 3)
If an array called "data" had the values above stored in it, then the following call:
hasAlternatingParity(data) would return true. If instead the array stored the following values:
(2, 13, 4, 1, 0, 9, 2, 7, 4, 12, 3, 2)
then the call would return false because the list has two even numbers in a row (4 and 12). By definition, an empty list or a list of one element has alternating parity. You may assume that the values in the array are greater than or equal to 0.
Write your solution to hasAlternatingParity in Parity.java.
? Write a static method isAllEven that takes an array of integers as a parameter and that returns a boolean value indicating whether or not all of the values are even numbers (true for yes, false for no). For example, if a variable called list stores the following values:
(18, 0, 4, 204, 8, 4, 2, 18, 206, 1492, 42)
Then the call:
isAllEven(list)
should return true because each of these integers is an even number. If instead the list had stored these values:
(2, 4, 6, 8, 10, 208, 16, 7, 92, 14)
Then the call should return false because, although most of these values are even, the value 7 is an odd number.
Write your solution to isAllEven in Even.java.
Explanation / Answer
Parity.java
public class Parity {
static boolean hasAlternatingParity(int[] data) {
int parity;
boolean status = true;
if (data[0] % 2 == 0) {
parity = 0;
} else {
parity = 1;
}
for (int i = 1; i < data.length; i++) {
if (data[i] % 2 == 0 && parity == 0) {
status = false;
break;
} else if (data[i] % 2 == 0 && parity == 1) {
parity = 0;
} else if (data[i] % 2 != 0 && parity == 1) {
status = false;
break;
} else if (data[i] % 2 != 0 && parity == 0) {
parity = 1;
}
}
return status;
}
public static void main(String[] args) {
int[] array1 = { 3, 2, 19, 8, 43, 64, 1, 0, 3 };
int[] array2 = { 2, 13, 4, 1, 0, 9, 2, 7, 4, 12, 3, 2 };
System.out.println(hasAlternatingParity(array1));
System.out.println(hasAlternatingParity(array2));
}
}
Even.java
public class Even {
static boolean isAllEven(int[] list) {
boolean status = true;
for (int i = 0; i < list.length; i++) {
if (list[i] % 2 != 0) {
status = false;
break;
}
}
return status;
}
public static void main(String[] args) {
int[] array1 = { 18, 0, 4, 204, 8, 4, 2, 18, 206, 1492, 42 };
int[] array2 = { 2, 4, 6, 8, 10, 208, 16, 7, 92, 14 };
System.out.println(isAllEven(array1));
System.out.println(isAllEven(array2));
}
}