Saturday 30 September 2017

Java method that takes an array of int values and determines if there is a pair of distinct elements of the array whose product is even

Problem:

Write a short Java method that takes an array of int values and determines if there
is a pair of distinct elements of the array whose product is even.

Solution:

package com.basics;

import java.util.Scanner;

public class FindProductOfArrayDistinctElements {

int numberArray[];
int arrayLimit;

public static void main(String[] args) {
FindProductOfArrayDistinctElements findProductOfArrayDistinctElements = new FindProductOfArrayDistinctElements();
findProductOfArrayDistinctElements.initializeArray();
System.out.println("is the given array contains a pair of distinct elements whose product is even. " + findProductOfArrayDistinctElements.isEvenProduct());
}

public void initializeArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("how many numbers you want to store in an array");
arrayLimit = scanner.nextInt();
numberArray = new int[arrayLimit];
for (int i = 0; i < numberArray.length; i++) {
System.out.println("enter the number");
numberArray[i] = scanner.nextInt();
}
scanner.close();
}

public boolean isEvenProduct(){
boolean isEvenProduct = false;
for (int i = 0; i < numberArray.length; i++) {
for (int j = 1; j < numberArray.length; j++) {
if(numberArray[i] != numberArray[j] && ((numberArray[i] * numberArray[j]) % 2 == 0)){
isEvenProduct = true;
}
}
}
return isEvenProduct;
}


}


Output:

how many numbers you want to store in an array
3
enter the number
3
enter the number
5
enter the number
3
is the given array contains a pair of distinct elements whose product is even. false


how many numbers you want to store in an array
3
enter the number
2
enter the number
4
enter the number
2
is the given array contains a pair of distinct elements whose product is even. true


how many numbers you want to store in an array
2
enter the number
2
enter the number
2
is the given array contains a pair of distinct elements whose product is even. false


how many numbers you want to store in an array
5
enter the number
3
enter the number
3
enter the number
3
enter the number
3
enter the number
3
is the given array contains a pair of distinct elements whose product is even. false


No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...