简体   繁体   English

从已排序的数组中删除0值?

[英]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: 我想知道是否有办法删除我运行以下代码时得到的默认“0”值:

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. 它成功地将任何数字排序为正确的顺序,然而,总是有这个令人讨厌的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? 我不打算删除所有0(我希望用户能够输入0并让它显示) - 我只是不想要默认的0.任何想法?

Array indexes in Java are 0-based, not 1-based. Java中的数组索引是从0开始的,而不是从1开始的。 So start iterating from 0 instead of from 1 and you should be good: 所以从0开始迭代而不是从1开始迭代你应该是好的:

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]. 当你分配一个大小为4的数组时,你要分配四个整数:i [0],i [1],i [2]和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). 因为Java非常友好,所以它将所有这四个设置为0.所以你在输出上看到的是[i[0],i[1],i[2],i[3]] (按排序顺序) )。 The sort isn't adding the 0, it was already there. 排序不是添加0,它已经存在了。 If you only want 3 numbers, then you should allocate an int[3] rather than an int[4]. 如果你只想要3个数字,那么你应该分配一个int [3]而不是int [4]。 And then, to go along with that, when you ask for number 1, store it in i[0]. 然后,与此同时,当您要求编号1时,将其存储在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. 大多数程序员都会从0到2,然后在与用户交谈时输出i + 1。

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. 正如其他人所指出的那样,问题是你的int应该从0开始,而不是1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM