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:
Arraylists
Exercise:
Exercises
Question:9 | ISBN:9780136091813 | Edition: 2

Question

Write a method called rangeBetweenZeroes that takes as a parameter an ArrayList of integers and returns the number of indexes apart the two furthest occurrences of the number 0 are. For example, if the list stores the values (7, 2, 0, 0, 4, 0, 9, 0, 6, 4, 8) when the method is called, it should return 6, because the occurrences of 0 that are furthest apart are at indexes 2 and 7, and the range 2 through 7 has six elements. If only one 0 occurs in the list, your method should return 1 . If no 0 s occur, your method should return 0.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Implementation of rangeBetweenZeroes method:

	public static int rangeBetweenZeroes(ArrayList intList)
	{		
		boolean found = false;
		int minIndex = 0;
		int maxIndex = 0;
				
		for(int i = 0; i < intList.size(); i++)
		{	
			if(intList.get(i) == 0 && !found)
			{
				found = true;
				minIndex = i;
			}
			
			if(intList.get(i) == 0 && found)
			{
				maxIndex = i;
			}
		}
		
		if(found)
			return (maxIndex - minIndex + 1);
		else
			return 0;
	}
0 0

Discussions

Post the discussion to improve the above solution.