I am trying to write a program that will, when executed, will go through an array and remove all instances of 0.0 and change the size of the array equal to the number of non zero elements and put those elements in their previous order. That is, if n=10 and the contents of a[j], j = 0 to n – 1 are initially
0.0, 1.2, 0.0, 0.0, 0.0, 2.3, 0.0, 9.7, 5.6, 0.0
then after execution of the code the contents should be
n=4, a[0]=1.2, a[1]=2.3, a[2]=9.7, and a[3]=5.6.
This is what I have so far:
import java.util.Scanner;
public class hw2
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
final double KEY = 0.0;
int n = scan.nextInt();
double[] a = new double[n];
for(int i=0; i<n; i++)
{
a[i] = scan.nextDouble();
}
for(int k = 0; k<n; k++)
{
if(a[k] == KEY)
{
a[k] = a[k+1];
n--;
}
System.out.println(a[k]);
}
}
}
Just a little nudge in the right direction would be appreciated.
Your implementation (2nd for loop) is not right, it will fail to simple test case:
Input > 5 2.0 2 0.0 3 0.0
Your program will have wrong output:
2.0
2.0
3.0
3.0
but it should be 2.0 2.0 3
Also, you can’t use == to compare two double.
The following code is my solution basing on your current code:
Also I prefer to use an ArrayList like below: