469,267 Members | 1,056 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,267 developers. It's quick & easy.

Printing out a Random Array

import java.util;

public class Compact
{
public static int[] randomArray (int n)
{
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = Math.random();
}
return a;
}

public static double[] printArray (double[] a)
{
for (int i = 0; i<a.length; i++)
{
return a[i];
}
}

public static void main(String args[])
{
System.out.println("Test for printing " + printArray(a));
}
}


In the above code, what I am trying to do is create an array with random integers. The size of the array is 20. I don't know how to call the array...
Dec 6 '07 #1
47 3559
JosAH
11,448 Expert 8TB
Have you tried to compile it and read what the compiler had to say about it? btw,
you can't call an array, you might yell 'yoohoo' at it but I'm sure it won't react nor
respond. Arrays are kind of stupid.

kind regards,

Jos
Dec 6 '07 #2
Have you tried to compile it and read what the compiler had to say about it? btw,
you can't call an array, you might yell 'yoohoo' at it but I'm sure it won't react nor
respond. Arrays are kind of stupid.

kind regards,

Jos

import java.util;

public class Compact
{
public static void main(String[] args)
{
public static int[] randomArray (int n)
{
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = Math.random();
}
System.out.println (a);
}
}
}


this doesn't work for some reason, it says illegal start of expression at the randomArray method. and a semicolon is expected at the second to last bracket
Dec 6 '07 #3
BigDaddyLH
1,216 Expert 1GB
When your syntax is way off the mark, the resulting compiler messages may not be helpful, because the compiler is so confused. That is the case, here.

You nested the defintion of method randomArray inside method main. In other words, you wrote:

Expand|Select|Wrap|Line Numbers
  1. void f() {
  2.     void g() {
  3.  
  4.     }
  5. }
  6.  
instead of

Expand|Select|Wrap|Line Numbers
  1. void f() {
  2.  
  3. }
  4.  
  5. void g() {
  6.  
  7. }
  8.  
Dec 6 '07 #4
When your syntax is way off the mark, the resulting compiler messages may not be helpful, because the compiler is so confused. That is the case, here.

You nested the defintion of method randomArray inside method main. In other words, you wrote:

Expand|Select|Wrap|Line Numbers
  1. void f() {
  2.     void g() {
  3.  
  4.     }
  5. }
  6.  
instead of

Expand|Select|Wrap|Line Numbers
  1. void f() {
  2.  
  3. }
  4.  
  5. void g() {
  6.  
  7. }
  8.  
okay, one problem was fixed. But it still says "illegal start of expression" for the random array method.
Dec 7 '07 #5
BigDaddyLH
1,216 Expert 1GB
okay, one problem was fixed. But it still says "illegal start of expression" for the random array method.
I can only guess what your code looks like now. I suggest that when you are asking a question about a syntax error, you should post the relevant code.
Dec 7 '07 #6
I can only guess what your code looks like now. I suggest that when you are asking a question about a syntax error, you should post the relevant code.
srry

import java.util;

public class Compact
{
public static void main(String[] args)
{
public static int[] randomArray(int n)
{
int[] a = new int[n];
for (int i = 0; i < a.length; i++)
{
a[i] = Math.random();
}
}
System.out.println (a);
}
}
Dec 7 '07 #7
JosAH
11,448 Expert 8TB
Your first line is wrong: you can't import a package, you import classes instead;
as in:

Expand|Select|Wrap|Line Numbers
  1. import java.util.*;
  2.  
Compilers can be real nitpickers (which is AGT (A Good Thing (tm)))

kind regards,

Jos
Dec 7 '07 #8
BigDaddyLH
1,216 Expert 1GB
You are still nesting method randomArray inside method main. See reply #4.

ps. If you use code tags, your code will be more readable in this forum.
Dec 7 '07 #9
Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         public static int[] randomArray(int n)
  8.         {
  9.             int[] a = new int[n];
  10.             for (int i = 0; i < a.length; i++)
  11.             {
  12.             a[i] = Math.random();
  13.             }
  14.         }
  15.             System.out.println (a);
  16.     }
  17. }
  18.  
Still doesn,t work, same error
Dec 7 '07 #10
BigDaddyLH
1,216 Expert 1GB
See reply #9 -- I think it was posted just as you were replying!
Dec 7 '07 #11
See reply #9 -- I think it was posted just as you were replying!
Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static int[] randomArray(int n)
  6.     {
  7.         int[] a = new int[n];
  8.         for (int i = 0; i < a.length; i++)
  9.         {
  10.         a[i] = Math.random();
  11.         }
  12.         return a;
  13.     }
  14.  
  15.  
  16.     public static void main(String args[])
  17.     {
  18.         int k;
  19.  
  20.         System.out.println("The random array is: " + randomArray(k));
  21.     }
  22. }
It says i have a possible loss of precision at a[i] = Math.random()
Dec 7 '07 #12
Laharl
849 Expert 512MB
Math.random() returns a decimal value in the range 0 <= x < 1. Thus, it is not an integer, but rather a double or float (I'm guessing double). To resolve this, you need to either use the Random class (google it) or cast Math.random() to an integer after multiplying to get the range you want.

For 0<=x<10 (aka random numbers less than 10):
Expand|Select|Wrap|Line Numbers
  1. import java.util.Random; //util.* covers this
  2. public class A {
  3.  public static void main(String[] args){
  4.   int[] a = new int[8];
  5.   for (int b = 0; b < a.length; b++)
  6.     a[b] = (int)(Math.random()*10);
  7.  }
  8. }
  9.  
Dec 8 '07 #13
Math.random() returns a decimal value in the range 0 <= x < 1. Thus, it is not an integer, but rather a double or float (I'm guessing double). To resolve this, you need to either use the Random class (google it) or cast Math.random() to an integer after multiplying to get the range you want.

For 0<=x<10 (aka random numbers less than 10):
Expand|Select|Wrap|Line Numbers
  1. import java.util.Random; //util.* covers this
  2. public class A {
  3.  public static void main(String[] args){
  4.   int[] a = new int[8];
  5.   for (int b = 0; b < a.length; b++)
  6.     a[b] = (int)(Math.random()*10);
  7.  }
  8. }
  9.  
Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static void main(String args[])
  6.     {    
  7.         int a[] = new int[20];    
  8.  
  9.         public static int[] randomArray(int a)
  10.         {            
  11.             for (int i = 0; i < a.size() ; i++)
  12.             {
  13.                 a[i] = (int)(Math.random() * 10);
  14.             }
  15.             System.out.println("The random array is: " + a);
  16.         }
  17.     }
  18. }
  19.  
Still didn't work.
Dec 8 '07 #14
Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static void main(String args[])
  6.     {    
  7.         int a[] = new int[20];    
  8.  
  9.         for (int i = 0; i < a.length ; i++)
  10.             {
  11.                 a[i] = (int)(Math.random() * 10);
  12.             }
  13.  
  14.         System.out.println("The random array is: " + a);
  15.  
  16.     }
  17. }
  18.  
Okay, it has random stuff in it when it is printed out and it doesn't go to 20.
Dec 8 '07 #15
BigDaddyLH
1,216 Expert 1GB
Why not use java.util.Arrays? You're importing it:
Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact {
  4.     public static void main(String[] args) {
  5.         int a[] = new int[20];
  6.         for (int i = 0; i < a.length ; i++) {
  7.             a[i] = (int)(Math.random() * 10);
  8.         }
  9.         System.out.println("The random array is: " 
  10.             + Arrays.toString(a));
  11.     }
  12. }
The reason you were not getting the right output before is because the toString method for arrays doesn't output their contents.
Dec 8 '07 #16
Laharl
849 Expert 512MB
Your code as it is will print out the memory address of the array, not the actual elements. The identifier on an array, when passed to System.out.println() does not work like the identifier for a primitive type, such as an integer. Instead, it prints out the memory location.

Expand|Select|Wrap|Line Numbers
  1. System.out.println(a); //Only prints a's address, since a is actually a pointer to the array
  2.  
  3. for (int b = 0; b < a.length; b++) //Prints out each address on one line, then a newline
  4.  System.out.print(a[b]+" ");
  5. System.out.println(); //Newline
  6.  
Dec 8 '07 #17
Your code as it is will print out the memory address of the array, not the actual elements. The identifier on an array, when passed to System.out.println() does not work like the identifier for a primitive type, such as an integer. Instead, it prints out the memory location.

Expand|Select|Wrap|Line Numbers
  1. System.out.println(a); //Only prints a's address, since a is actually a pointer to the array
  2.  
  3. for (int b = 0; b < a.length; b++) //Prints out each address on one line, then a newline
  4.  System.out.print(a[b]+" ");
  5. System.out.println(); //Newline
  6.  
I got it working, thanks
Dec 8 '07 #18
I got it working, thanks
Okay, now that that is done. I have another problem.

I want to get rid of all of the zeroes in the random array. For example, the output would look something like this.

1 0 2 3 4 5 6 7 8 0 9 9 8 7 6 5 4 3 2 1 //Prints out the initial random array
1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 1 //Prints out the same array but without the zeroes.


So here is my idea

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static void main(String args[])
  6.     {    
  7.         int a[] = new int[20];    
  8.  
  9.         for (int i = 0; i < a.length; i++)
  10.             {
  11.                 int b = (int) (Math.random() * 10);
  12.                 a[i] = b;
  13.                 System.out.print(a[i] + " ");
  14.             }
  15.  
  16.         for (int k = 0; k < a.length; k++)
  17.             {
  18.                 if (a[k] == 0)
  19.                 {
  20.                     //remove a zero
  21.                     int temp = a[k];
  22.                 }
  23.             }    
  24.     }
  25. }
  26.  
  27.  
So what I am trying to do is store all the zeroes in temp, then when i print out the random array without the zeroes, i'll just subtract temp from it.
Dec 8 '07 #19
Laharl
849 Expert 512MB
There's a simpler way to do this. Simply use an if statement, saying if a[i]!=0, execute the printing code. That way, all the nonzero elements get printed, without any annoying removal code. If you really want to do that, I'd recommend an ArrayList.
Dec 8 '07 #20
There's a simpler way to do this. Simply use an if statement, saying if a[i]!=0, execute the printing code. That way, all the nonzero elements get printed, without any annoying removal code. If you really want to do that, I'd recommend an ArrayList.

It's an assignment, and I'm not allowed to use ArrayList
Dec 8 '07 #21
Laharl
849 Expert 512MB
Selective printing (the if statement) is by far the easiest solution. If you actually have to remove the zeroes, this problem is far more difficult.
Dec 8 '07 #22
Selective printing (the if statement) is by far the easiest solution. If you actually have to remove the zeroes, this problem is far more difficult.

I have to remove the zeros
Dec 8 '07 #23
Laharl
849 Expert 512MB
Given that arrays cannot be resized, you'll need a new array composed of the nonzero elements of the original. If you're limited to one array, you can push the zeroes to either end, then print either starting from the first nonzero or ending at the last end.
Dec 8 '07 #24
Given that arrays cannot be resized, you'll need a new array composed of the nonzero elements of the original. If you're limited to one array, you can push the zeroes to either end, then print either starting from the first nonzero or ending at the last end.
oh. So i just move the zeroes to the end and print out the first non zero integer all the way to the last non zero integer? How do I do that? I was thinking about using a for loop and adding it to the last one. So when the for loop hits the last integer, all the zeros would go to the end.
Dec 9 '07 #25
Laharl
849 Expert 512MB
Kind of. When you find the first zero, you want to switch it with the last element. The second, the second to last element. And so on. To do this, you can keep track of how many you've found and access the appropriate element near the end to switch with (length-count, make sure you increment count at the right time). Note that if the element you're trying to switch with is a zero, you have to move to the next element towards the front until you have a nonzero to switch with.
Dec 9 '07 #26
Kind of. When you find the first zero, you want to switch it with the last element. The second, the second to last element. And so on. To do this, you can keep track of how many you've found and access the appropriate element near the end to switch with (length-count, make sure you increment count at the right time). Note that if the element you're trying to switch with is a zero, you have to move to the next element towards the front until you have a nonzero to switch with.
wouldn't that just switch the array around?

for example

1 0 0 2 3 4 5 6 7 8 0 9 2 1 4 6 0 4 // regular array
1 4 0 2 3 4 5 6 7 8 6 9 2 1 4
Dec 9 '07 #27
JosAH
11,448 Expert 8TB
If you don't want zeros in your array, I'd say don't put them in there in the first place.

kind regards,

Jos
Dec 9 '07 #28
If you don't want zeros in your array, I'd say don't put them in there in the first place.

kind regards,

Jos

well, its kind of an assignment. First I have to print out the random array, then i print out that array without zeros
Dec 9 '07 #29
JosAH
11,448 Expert 8TB
well, its kind of an assignment. First I have to print out the random array, then i print out that array without zeros
Simply iterate (loop) over the array; if you see a non-zero number then print it,
otherwise skip it (i.e. do nothing).

kind regards,

Jos
Dec 9 '07 #30
Simply iterate (loop) over the array; if you see a non-zero number then print it,
otherwise skip it (i.e. do nothing).

kind regards,

Jos

One of the assignment rules is
Do not solve the problem by printing out only the non-zero values in the array
Dec 9 '07 #31
Laharl
849 Expert 512MB
wouldn't that just switch the array around?

for example

1 0 0 2 3 4 5 6 7 8 0 9 2 1 4 6 0 4 // regular array
1 4 0 2 3 4 5 6 7 8 6 9 2 1 4
Yup. If you want them actually taken out, loop through, count how many zeroes there are, and make a new array with the number of nonzero elements in the original. Then feed all the nonzero elements into that array and print.
Dec 9 '07 #32
1. Write a program that creates an array of random integers. Use a constant for the size of the array.

2. Write a method compact that removes all zeroes from the array, leaving the order of the other elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.

3. Do not solve the problem by printing out only the non-zero values in the array. The compact method must remove all zeros from the array.
Dec 9 '07 #33
1. Write a program that creates an array of random integers. Use a constant for the size of the array.

2. Write a method compact that removes all zeroes from the array, leaving the order of the other elements unchanged. All local variables within this function must be scalar. In other words, you may not use a second array to solve the problem.

3. Do not solve the problem by printing out only the non-zero values in the array. The compact method must remove all zeros from the array.

I have an idea, but i don't know how to put it in. After it prints out the first random array. The method, Compact, will run as a for loop. then each element goes through a cleaner method and returns the cleaned element, cleaning meaning it will get rid of zeros. So if it is a zero, it will be equal to null. But I don't know how to type that...

and what's wrong with this code?

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.  
  6.     public static int[] randomArray(int[] n)
  7.     {
  8.         for (int i = 0; i < n.length; i++)
  9.             {
  10.                 int b = (int) (Math.random() * 100);
  11.                 n[i] = b;
  12.                 return n[i];
  13.             }
  14.     }
  15.  
  16.     /*    for (int i = 0; i < a.length; i++)
  17.             {
  18.  
  19.             }
  20. */
  21. public static void main(String args[])
  22. {
  23.     int a[] = new int[20];
  24.  
  25.     System.out.print(randomArray(a) + " ");
  26. }        
  27. }
  28.  
Dec 9 '07 #34
Laharl
849 Expert 512MB
That doesn't work, as null is not an integer, so it can't be put into an array of integers. If you used Integers, this will work, as an Integer is an object, and thus can be null.

Frankly, I don't think this actually is possible, as to the best of my knowledge, arrays have static size determined at creation, which then can't be changed. Thus, you can't actually remove elements from an array. You can make them into something that gets skipped over based on your code (null), or shove them to one end.

Also, your printing code is still wrong. That will print out the address of the returned array, not the array itself. Call System.out.println(randomArray(a).toString()) instead.
Dec 9 '07 #35
JosAH
11,448 Expert 8TB
Use System.arraycopy() each time you 'see' a zero; copy the rest of the
array one element to the 'left'; keep a counter each time you do that and print
all the elements again except for the last 'count' elements.

kind regards,

Jos
Dec 9 '07 #36
Use System.arraycopy() each time you 'see' a zero; copy the rest of the
array one element to the 'left'; keep a counter each time you do that and print
all the elements again except for the last 'count' elements.

kind regards,

Jos
This is my code so far.

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays;
  2.  
  3. public class Compact 
  4. {
  5.     public static void main(String args[])
  6.     {
  7.         int a[] = new int[20];
  8.         int sum = 0;
  9.  
  10.         for (int i = 0; i < a.length; i++)
  11.             {
  12.                 int b = (int) (Math.random() * 10);
  13.                 a[i] = b;
  14.                 System.out.print(a[i] + " ");
  15.             }
  16.  
  17.         System.out.println();
  18.  
  19.         for (int k = 0; k < a.length; k++)
  20.             {
  21.                 if (a[k] == 0)
  22.                 {
  23.                     a[k] = a[k + 1];
  24.                     sum++;
  25.                 }
  26.             }
  27.  
  28.         for (int j = 0; j < a.length - sum; j++)
  29.             {
  30.                 System.out.print(a[j] + " ");
  31.             }
  32.     }    
  33. }
  34.  
The problem I'm having now is that the position where the zero was will be filled by the next number. But the next number will still be there, i need it to go down, or disappear..
Dec 9 '07 #37
Laharl
849 Expert 512MB
To swap two values in an array, you have to create a dummy variable to hold one of the values.

Expand|Select|Wrap|Line Numbers
  1. int temp = a[i];
  2. a[i]=a[i+1];
  3. a[i+1]=temp;
  4.  
To "remove" your zeroes and shove them to one end, you can use the method Jos suggested (Google it for more details). Your code is a good start for a different way to do it, but by swapping each zero with a[a.length-sum], as long as that value is not zero, (if it is, increment sum until you don't have a zero or you get back to the current value), your printing loop should work fine.
Dec 9 '07 #38
JosAH
11,448 Expert 8TB
w.r.t. this hackery, also read a little article I wrote in the 'Howtos' section named
'Old tricks' (or similar). IMHO the OP should start to learn programming because
there's nothing Java specific about moving array elements around.

kind regards,

Jos
Dec 9 '07 #39
Okay, i got it working but there is one problem

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays; //Imports Array Package
  2.  
  3. public class Compact //Creates Class Compact
  4. {
  5.     public static void main(String args[]) //Main Method
  6.     {
  7.         /*Variables*/
  8.         int a[] = new int[20];
  9.         int sum = 0;
  10.  
  11.         /*First for loop prints out the random array*/
  12.         for (int i = 0; i < a.length; i++)
  13.             {
  14.                 int b = (int) (Math.random() * 10);
  15.                 a[i] = b;
  16.                 System.out.print(a[i] + " ");
  17.             }
  18.  
  19.         /*Prints out a blank line*/
  20.         System.out.println();
  21.  
  22.         /*Second for loop returns the random array without zeros*/
  23.         for (int k = 0; k < a.length - 1; k++)
  24.             {
  25.                 if (a[k] == 0)
  26.                 {
  27.                     for (int m = k; m < a.length - 1; m++)
  28.                     {
  29.                         for (int n = 0; n < a.length - 1; n++)
  30.                         {
  31.                         }
  32.                     }
  33.                     sum++;
  34.                 }
  35.             }
  36.  
  37.         //Prints out the array without zeros
  38.         for (int j = 0; j < a.length - sum; j++)
  39.             {
  40.                 System.out.print(a[j] + " ");
  41.             }
  42.     }    
  43. }
  44.  
What I'm trying to do in the second for loop is found out if the next integer is a zero, then I'll remove them...But I don't know how.
For example

1 0 0 2 3 4 <--Initial Array
1 2 3 4 <--Compact Array

but my code will output this

1 0 2 3 4

because it takes the next integer. So i need something that will check whether or not the next integer is a zero...
Dec 10 '07 #40
Laharl
849 Expert 512MB
You can use [i+1] to access the next element in the array, but you will need to make sure that you don't go out of bounds.
Dec 10 '07 #41
You can use [i+1] to access the next element in the array, but you will need to make sure that you don't go out of bounds.

I don't exactly know where and how to put it.
Dec 10 '07 #42
I don't exactly know where and how to put it.
I tried doing it, but I'm getting an out of bounds error

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays; //Imports Array Package
  2.  
  3. public class Compact //Creates Class Compact
  4. {
  5.     public static void main(String args[]) //Main Method
  6.     {
  7.         /*Variables*/
  8.         int a[] = new int[20];
  9.         int sum = 0;
  10.  
  11.         /*First for loop prints out the random array*/
  12.         for (int i = 0; i < a.length; i++)
  13.             {
  14.                 int b = (int) (Math.random() * 10);
  15.                 a[i] = b;
  16.                 System.out.print(a[i] + " ");
  17.             }
  18.  
  19.         /*Prints out a blank line*/
  20.         System.out.println();
  21.  
  22.         /*Second for loop returns the random array without zeros*/
  23.         for (int k = 0; k < a.length - 1; k++)
  24.             {
  25.                 if (a[k] == 0)
  26.                 {
  27.                     //It needs to check if the next integer is zero. If it is
  28.                     //then it needs to go to the next one.
  29.                     for (int i = 1; i < a.length - 1; i++)
  30.                     {
  31.                         if (a[k + i] == 0)
  32.                         {
  33.                             a[k] = a[k + i + 1];
  34.                         }
  35.                         else
  36.                         {
  37.                             a[k] = a[k + 1];
  38.                         }
  39.                     }
  40.                     sum++;
  41.                 }
  42.             }
  43.  
  44.         //Prints out the array wihtout zeros
  45.         for (int j = 0; j < a.length - sum; j++)
  46.             {
  47.                 System.out.print(a[j] + " ");
  48.             }
  49.     }    
  50. }
  51.  
Dec 10 '07 #43
Laharl
849 Expert 512MB
You have to check if k+i (or k+i+1) < a.length to use that method. You also have some logical issues in the assignment code, as the value from farther in the array is not swapped down to the original location of the 0.

It's a start, though. Also, to be efficient, you don't need to loop through the entire array in the inner loop, as the parts of the array you've already seen can be known to not be zero, so you can start from i=k.
Dec 10 '07 #44
You have to check if k+i (or k+i+1) < a.length to use that method. You also have some logical issues in the assignment code, as the value from farther in the array is not swapped down to the original location of the 0.

It's a start, though. Also, to be efficient, you don't need to loop through the entire array in the inner loop, as the parts of the array you've already seen can be known to not be zero, so you can start from i=k.
I'm not sure I follow. Sorry, I'm still new at Java.

Expand|Select|Wrap|Line Numbers
  1. import java.util.Arrays; //Imports Array Package
  2.  
  3. public class Compact //Creates Class Compact
  4. {
  5.     public static void main(String args[]) //Main Method
  6.     {
  7.         /*Variables*/
  8.         int a[] = new int[20];
  9.         int sum = 0;
  10.  
  11.         /*First for loop prints out the random array*/
  12.         for (int i = 0; i < a.length; i++)
  13.             {
  14.                 int b = (int) (Math.random() * 10);
  15.                 a[i] = b;
  16.                 System.out.print(a[i] + " ");
  17.             }
  18.  
  19.         /*Prints out a blank line*/
  20.         System.out.println();
  21.  
  22.         /*Second for loop returns the random array without zeros*/
  23.         for (int k = 0; k < a.length - 1; k++)
  24.             {
  25.                 if (a[k] == 0)
  26.                 {
  27.                     //It needs to check if the next integer is zero. If it is
  28.                     //then it needs to go to the next one.
  29.                     for (int i = k; i < a.length; i++)
  30.                     {
  31.                         if (a[k + i] == 0)
  32.                         {
  33.                             if (a[k + i + 1] < a.length);
  34.                             a[k] = a[k + i + 1];
  35.                         }
  36.                         else
  37.                         {
  38.                             a[k] = a[k + 1];
  39.                         }
  40.                     }
  41.                     sum++;
  42.                 }
  43.             }
  44.  
  45.         //Prints out the array wihtout zeros
  46.         for (int j = 0; j < a.length - sum; j++)
  47.             {
  48.                 System.out.print(a[j] + " ");
  49.             }
  50.     }    
  51. }
  52.  
Would it be something like that?
Dec 10 '07 #45
Laharl
849 Expert 512MB
It is something like that, only not quite. You want to check if a[i] is 0 as well each time. If it is, you don't want to do anything immediately. If it isn't, you can set a[k] to a[i] and a[i] to 0, and then use a break; statement to leave the loop.

Also, since you're sliding zeroes down the array a few spots at a time, each zero is going to come up several times. Thus, sum is going to be much larger than the actual number of zeroes. You're better off doing your counting up at the top, when you're filling the array.
Dec 10 '07 #46
JosAH
11,448 Expert 8TB
Oh dear; this thread is approaching 50 replies already; a serious sign that this
little problem will never be solved. The OP should design a bit first before writing
almost random code.

Think of an index 't' ('t' for trash). Starting at that index value and to the right of it
the array contains trash. Initially t == array.length.

Also think of an index 'i' that iterates over the interval [0, t) (exclusive). Each time
array[i] equals zero move the elements in the interval [i+1, t) to [i, t-1) and
decrement t. If the element array[i] was zero, don't increment i.

Repeat until i >= t and you're done.

kind regards,

Jos
Dec 10 '07 #47
BigDaddyLH
1,216 Expert 1GB
Perhaps some example code is in order.

Expand|Select|Wrap|Line Numbers
  1. public class Shift {
  2.     void shift(int[] source) {
  3.         int[] destination = new int[source.length];
  4.         int di = 0;
  5.         for(int si=0; si<source.length; si++) {
  6.             if (isEven(source[si])) {
  7.                 destination[di] = source[si];
  8.                 di++;
  9.             }
  10.         }
  11.         //here di is the count of elements copied to destination
  12.         //...
  13.     }
  14.  
  15.     boolean isEven(int n) {
  16.         return n % 2 == 0;
  17.     }
  18. }
This code copies the even numbers from source to destination. Because the two arrays have the same length, there may be unused cells in destination, but after the loop, you know the count of elements copied is di.

Question: what if I hadn't created a second array and just copied from the given array back to itself? Hmmm...
Dec 10 '07 #48

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

10 posts views Thread by Virus | last post: by
16 posts views Thread by Jason | last post: by
10 posts views Thread by Johnny Snead | last post: by
4 posts views Thread by Arif | last post: by
5 posts views Thread by jar13861 | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.