SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:20 | ISBN:9781118771334 | Edition: 6

Question

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).

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package java_problems_datastructures;

import java.util.Scanner;

public class CheckDistinctValues {

	// by default we set the boolean value to be true

	static boolean isElementsDistinct = true;

	public static boolean uniqueValues(float[] values) {

		// loop over the elements by taking j as initial index and k as next index

		for (int j = 0; j < values.length; j++) {

			for (int k = j + 1; k < values.length; k++) {

				// if values in index j and index k are same we change default value to be
				// false;

				if (k != j && values[k] == values[j])
					isElementsDistinct = false;

			}
		}

		return isElementsDistinct;

	}

	public static void main(String args[]) {
		Scanner input = new Scanner(System.in);
		System.out.println("please enter size of array:  ");
		int size = input.nextInt();
		float[] floatArray = new float[size];
		System.out.println("enter " + size + " float values: ");
		for (int i = 0; i < floatArray.length; i++) {

			floatArray[i] = input.nextFloat();
		}

		// float[] values = new float[] { 2.5f, 7f, 32.8f, 89f, 0.09f, 3f, 6.3f };

		System.out.println("Are the elemens distinct? " + uniqueValues(floatArray));

		input.close();

	}

}


Output:

please enter size of array:  
4
enter 4 float values: 
21
1
2
2
Are the elemens distinct? false

 

0 0

Discussions

Post the discussion to improve the above solution.