开发者

Removing the 0 value from a sorted Array?

I was wonderin开发者_StackOverflow中文版g 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?


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++ )


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


When you allocate an array of size 4, you're allocating four ints: i[0],i[1],i[2], and i[3]. Because Java is fairly friendly, it sets all four of these to 0. So what you're seeing on the output is [i[0],i[1],i[2],i[3]] (in sorted order). The sort isn't adding the 0, it was already there. If you only want 3 numbers, then you should allocate an int[3] rather than an int[4]. And then, to go along with that, when you ask for number 1, store it in i[0]. The simplest change to do this would be to simply change the top line to

 int [] x = new int[3];

and the later line to

 x[i-1] = scan.nextInt();

The change suggested by other answers is the more common, one, though. Most programmers would have i go from 0 to 2 and then output i+1 when talking to the user.


The following code should work:

Scanner scan = new Scanner(System.in);

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

The problem was, as others have pointed out, that your int i should start at 0, not 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜