Saturday 30 September 2017

Java method that takes an array of float values and determines if all the numbers are different from each other (that is, they are distinct).

Problem:

Write a Java method that takes an array of float values and determines if all the
numbers are different from each other (that is, they are distinct).

Solution:

package com.basics;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class ArrayHasDistnctFloatNumbers {

float[] floatNumbers;
int arrayLimit;

public static void main(String[] args) {
ArrayHasDistnctFloatNumbers arrayHasDistnctFloatNumbers = new ArrayHasDistnctFloatNumbers();
arrayHasDistnctFloatNumbers.initializeTheArray();
System.out.println("is the given array has distinct float numbers ?? " + arrayHasDistnctFloatNumbers.distinctValues());
}

public void initializeTheArray(){
Scanner scanner = new Scanner(System.in);
System.out.println("enter the array limit");
arrayLimit = scanner.nextInt();
floatNumbers = new float[arrayLimit];
for (int i = 0; i < floatNumbers.length; i++) {
System.out.println("enter the float value");
floatNumbers[i] = scanner.nextFloat();
}

scanner.close();
}

public  boolean distinctValues(){
    Set<Float> foundNumbers = new HashSet<Float>();
    for (float num : floatNumbers) {
        if(foundNumbers.contains(num)){
            return false;
        }
        foundNumbers.add(num);
    }             
    return true;         
}

}


Output:

enter the array limit
3
enter the float value
2.34
enter the float value
4.56
enter the float value
5.67
is the given array has distinct float numbers ?? true


enter the array limit
3
enter the float value
3.45
enter the float value
4.56
enter the float value
3.45
is the given array has distinct float numbers ?? 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...