Results 1 to 10 of 10
  1. #1
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Post Manipulating array elements to zero using for-loops and if-statements in Java

    So I've been working on my Java CompSci assignment, and I've spent quite some time getting to where I am and I just need one final push over the hill.
    The first part I've finished, it was to create a method called findZero that finds the first zero in an array and return the index. It works with what I think is one exception. When the first zero in my array is also the last element in my array, it doesn't seem to work. I cannot see how to simply fix this. I could make the array one bigger than I need every time and not print the final integer, which I will do if no better ideas come to me.

    The second part is much more irksome. The assignment reads as follows:
    Write method setZeros. Method setZeros should find the positions of the first two zeroes in its array parameter A, and it should set all of the intervening values to zero. If A only contains one zero, or if the first two zeros are right next to each other, setZeros should not modify A.

    I was thinking that I'll first create a backup of the inputted array and use it to return if any of the no-edit conditions are true. As of now, I've used a combination of for loops and if statements to try to do what the programme design asks for, although my program currently replaces all zeroes after to first zero with zero.

    My code is available here:

    http://collabedit.com/2cu8d

    and I'll keep an eye on the chat there, although I'd prefer to discuss here and then I'll try to figure out the changes.

    Any and all help, advice, or comments are much appreciated.

    Example of current output at 25 elements

    http://collabedit.com/53swq

    Any questions of information I've not given welcome.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by paulmmj View Post
    So I've been working on my Java CompSci assignment, and I've spent quite some time getting to where I am and I just need one final push over the hill.
    The first part I've finished, it was to create a method called findZero that finds the first zero in an array and return the index. It works with what I think is one exception. When the first zero in my array is also the last element in my array, it doesn't seem to work. I cannot see how to simply fix this. I could make the array one bigger than I need every time and not print the final integer, which I will do if no better ideas come to me.
    For both questions, it's better if you post code in the forum, not at another site. So for the benefit of all, here's your code:

    Java Code:
    public class ArrayManipulation {
       public int findZero(int array[], int pos) {
          int limit = array.length - 1;
          int retVal = -1; // Will remain -1 unless if statement in for loop returns
                           // true
    
          for (int i = pos; i < limit; i++) {
             if (array[i] == 0) // If element at location 'i' is zero, then ...
             {
                retVal = i; // make retVal the index location of first zero and ...
                i = limit; // breaks the for loop.
             }
          }
    
          return retVal;
       }
    
       public int[] setZeros(int array[]) {
          int limit = array.length - 1;
    
          for (int i = 0; i < limit; i++) {
             if (array[i] == 0) {
                int y = i + 1;
                for (int x = y; x < limit; x++) {
                   if (array[x] == 0)
                      x = limit;
                   else
                      array[x] = 0;
                }
             }
          }
          return array;
       }
    }


    For your first question, your for loop goes from pos to i < array.length - 1. Why not go to i < array.length?

    For your second question, a question of my own: why not use the first method to help you solve the second one?

  3. #3
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default

    For your first question, your for loop goes from pos to i < array.length - 1. Why not go to i < array.length?
    I believe array.length returns the actual number of elements, while I want to begin with zero. Am I wrong? ... Will test, haha.

    For your second question, a question of my own: why not use the first method to help you solve the second one?
    Of course! What a good idea! It never hit me. More good news - I think I've figured it out! I need to terminate both loops to make them both stop searching. I just did it and it seems to work! I've updated the code. I'll try and update in Eclipse to try to use my other method.

    Thanks, Fubarable.

    For both questions, it's better if you post code in the forum, not at another site.
    Sorry about that, I thought this was a trendy useful way of doing it, thanks for mentioning that.

    Java Code:
          for (int i = 0; i < limit; i++) { // Generic loop to go through every element
             if (array[i] == 0) { // If the element is zero ...
                int y = i + 1;
                for (int x = y; x < limit; x++) {
                   if (array[x] == 0)
                      x = limit;
                      i = limit;
                   else
                      array[x] = 0;
                }
             }
          }
    I think this will do the trick, but I can improve.

  4. #4
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    [QUOTE=paulmmj;177919]I believe array.length returns the actual number of elements, while I want to begin with zero. Am I wrong? [quote]

    If you have an array that has a length of 5 it has valid indicies of 0 - 4. You set limit to length - 1, limit = 4. you then loop while i < limit, less than 4. As such your loop will only check indicies 0 - 3. Thus missing the last element.

    The general way to loop over an array is index < length

  5. #5
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default


    If you have an array that has a length of 5 it has valid indicies of 0 - 4. You set limit to length - 1, limit = 4. you then loop while i < limit, less than 4. As such your loop will only check indicies 0 - 3. Thus missing the last element.

    The general way to loop over an array is index < length
    Makes a lot of sense, sorry I overlooked that, thank you for pointing that out. That's a nice general easy to apply way of doing it. Having applied the changes I learnt here, I believe I've found a sure-fire succint way of doing this:

    Java Code:
    public int findZero (int array[], int pos)
    	{
    		final int len = array.length;
    		int retVal = -1; // Will remain -1 unless if statement in for loop returns true
    
    		for (int i = pos; i < len; i++)
    		{
    			if (array[i] == 0) // If element at location 'i' is zero, then ...
    			{
    				retVal = i; // make retVal the index location of first zero and ...
    				i = len; // breaks the for loop.
    			}
    		}
    
    		return retVal;
    	}
    
    public int[] setZeros (int array[])
    	{
    		final int len = array.length;
    
    		int firstZero = findZero(array, 0) + 1;
    
    		for (int x = firstZero; x < len; x++)
    		{
    			if (array[x] == 0)
    			{
    				x = len;
    			}
    			else
    				array[x] = 0;
    		}
    		
    		return array;
    	}

  6. #6
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default

    Final full working version:

    Java Code:
    public class ArrayManipulation 
    {
    	public int findZero (int array[], int pos)
    	{
    		final int LEN = array.length;
    		int retVal = -1; // Will remain -1 unless if statement in for loop returns true
    
    		for (int i = pos; i < LEN; i++)
    		{
    			if (array[i] == 0) // If element at location 'i' is zero, then ...
    			{
    				retVal = i; // make retVal the index location of first zero and ...
    				i = LEN; // breaks the for loop.
    			}
    		}
    
    		return retVal;
    	}
    
    	public int[] setZeros (int array[])
    	{
    		final int LEN = array.length;
    		int firstZero = findZero(array, 0) + 1;
    		int numOfZero = numZeros(array);
    		
    		if (firstZero == -1)
    			return array;
    		
    		if (numOfZero < 2)
    			return array;
    
    		for (int x = firstZero; x < LEN; x++)
    		{
    			if (array[x] == 0)
    			{
    				x = LEN;
    			}
    			else
    				array[x] = 0;
    		}
    		
    		return array;
    	}
    	
    	private int numZeros (int array[])
    	{
    		final int LEN = array.length;
    		int numOfZeroes = 0;
    		for (int i = 0; i < LEN; i++)
    		{
    			if (array[i] == 0)
    				numOfZeroes++;
    		}
    		return numOfZeroes;
    	}
    
    
    
    }
    Thanks for all your help!

  7. #7
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    Glad you got it working but here is some food for thought:
    Java Code:
    public int findZero (int array[], int pos) {
        for (; pos < array.length; pos++) {
            if (array[pos] == 0) {
                return pos;
            }
        }
        return -1;
    }

  8. #8
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default

    Wow, that is a much more elegant code. Makes me feel brutish for having devised any other way, haha. Thank you sincerely for revealing that to me, it's moments like these that make computer science addicting... hahah.

    Similarly, I'm working on making my second method seem brutish by comparison, although I need a little push to get there, although I'm torturously close! What do you think of something like starting with the array position one after my first zero and beginning to look for zero's again. If the program doesn't find a zero, then the program ends. If it does, it takes that second index and manipulates everything between the two. ... But I don't know if it's possible.

    I'm thinking it should look something like this, but it's off, I get an out of bounds exception, trying to see through my useless human eyes which are telling me it should work, but alas, the computer does what I tell it not what I want it to do.

    Java Code:
    	public int[] setZeros2 (int array[])
    	{
    		int pos2 = pos + 1;
    		for (; pos < array.length; pos2++)
    		    if (array[pos2] == 0)
    		        for (; pos < pos2; pos++)
    		            array[pos] = 0;
    		return array;
    	}
    This is after setting the position of the first zero as a instance variable so as I can use it.

  9. #9
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default

    You are making it much harder than it needs to be. As Fubar mentioned you can use the findZero method that you have already written.

    Pseudocode:
    Java Code:
    start: call findZero with 0
    end: call findZero with one more than start
    loop from start to end {
        set array element to 0
    }
    return

  10. #10
    paulmmj is offline Member
    Join Date
    Oct 2010
    Posts
    14
    Rep Power
    0

    Default

    Wow, there we go. Thanks to all for finally getting me there. I'll be as good as you all someday, haha. Presently taking two Java classes, one at my high school and one at my community college. Really rather enjoying it, especially for those moments after realizing how incredibly dumb I HAD been, haha. Here's the final thing:

    Java Code:
    public class ArrayManipulation 
    {	
    	public int findZero (int array[], int pos) 
    	{
    		for (; pos < array.length; pos++) 
    			if (array[pos] == 0) 
    				return pos;
    		return -1;
    	}
    	
    	public int[] setZeros (int array[])
    	{
    		int start = findZero(array, 0);
    		int end = findZero(array, start + 1);
    		for (; start < end; start++)
    			array[start] = 0;
    		return array;
    	}
    }

Similar Threads

  1. sum of elements in array
    By myst in forum New To Java
    Replies: 7
    Last Post: 07-17-2010, 09:36 AM
  2. How array elements gets default value
    By Veangat in forum New To Java
    Replies: 1
    Last Post: 03-07-2010, 02:29 PM
  3. simple if statements and loops
    By merfen58 in forum New To Java
    Replies: 6
    Last Post: 09-22-2009, 10:46 AM
  4. Get value of a String into elements of an Array.
    By mainy in forum New To Java
    Replies: 1
    Last Post: 08-01-2009, 10:17 PM
  5. Help with array of elements
    By zoe in forum New To Java
    Replies: 1
    Last Post: 07-24-2007, 06:33 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •