Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing the 0 value from a sorted Array?

I was wondering if there was a way to remove the default "0" value I get when I run the following code:

Scanner scan = new Scanner(System.in);

int [] x = new int[4];
for ( int i = 1; i < x.length; i++ )
{
    System.out.println( "Enter number " + i + ": ");
    x[i] = scan.nextInt();
}
Arrays.sort(x);
System.out.println(Arrays.toString(x));
}

The output is as follows

[0, i[1], i[2], i[3]]

Of course, all the array values here are actually the numbers entered into the console. The code is WORKING. It successfully sorts any numbers into the correct order, however, there is always this nasty 0.

I'm not looking to remove ALL 0's (I want the user to be able to enter 0 and have it show up) - -I just don't want the default 0. Any ideas?

like image 825
Hanna Avatar asked Dec 29 '22 02:12

Hanna


2 Answers

Array indexes in Java are 0-based, not 1-based. So start iterating from 0 instead of from 1 and you should be good:

for ( int i = 0; i < x.length; i++ )
like image 126
dkarp Avatar answered Dec 30 '22 17:12

dkarp


for ( int i = 0; i < x.length; i++ )

like image 36
卢声远 Shengyuan Lu Avatar answered Dec 30 '22 15:12

卢声远 Shengyuan Lu