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:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a method hasOdd that accepts a set of integers as a parameter and returns true if the set contains at least one odd integer and false otherwise. If passed the empty set, your method should return false.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package collections;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

public class HasOdd {

    // this method takes the parameter of set
	public static boolean hasOdd(Set<Integer> set) {
		
       // checks for each value in the set, if it perfectly divides, it returns false
       // otherwise true 
		for(int value : set)
			if(value%2==1)
				return true;
		
		
		return false;
	}
	
	public static void main(String[] args) {

		Set<Integer> set = new HashSet<Integer>();
		Collections.addAll(set,4,6,4,5,4,2);
		System.out.println("does the given set has atleast one odd number: " +hasOdd(set));
	}

}
Output:

does the given set has atleast one odd number: true

 

0 0

Discussions

Post the discussion to improve the above solution.