简体   繁体   中英

Integers in array Java

I have an array that contains [45,8,50,15,65,109,2]. i would like to check to see if the zero element of my array is greater than my first element.

if ( 45 > 8) then i would like to add 45 to brand new sub array.
i would like to continue checking my array for anything that is bigger than 45 and add it to the new sub array. The new sub array has to keep the numbers added in the way they where added.The result should be [45,50,65,109]

I thought by creating this was going in the right direction but im doing something wrong so please help.

int[] x = [45,8,50,15,65,109,2];
int[] sub = null;
 for(int i = 0; i > x.length; i++) {
  for(int k = 0; k > x.length; k++) {
      if(x[i] > x[k]){
        sub = i;

First thing first. Your question contains some errors.

  1. you should write int[] x = {45,8,50,15,65,109,2}; instead of int[] x = [45,8,50,15,65,109,2]; You can not use [] to initialize array!

  2. What does it mean for(int i = 0; i > x.length; i++) . Your program must not run! Because, the value of i is less than x.langth . First condition check is false, so loop will not works!

  3. Same for for(int k = 0; k > x.length; k++)

  4. How do you want to store value in an array without index? You have to write sub[i] = x[i]; here, i means what index value you want to store where!

  5. Finally, do you want to do sorting ? If yes, then you need another variable named temp means temporary !

Try to clear the basic and after then try this code. Sorting Link

Best of Luck!

If you're trying to fetch everything greater than 0th element.

Use the following:

  1. Plain old java code:

     int[] x = {45,8,50,15,65,109,2}; int[] sub = new int[x.length]; int first = x[0]; sub[0]=first; int index=1; for(int i = 1; i < x.length; i++) { if(x[i] > first){ sub[index]=x[i]; index++; }}
  2. Streams API:

int[] x = {45, 8, 50, 15, 65, 109, 2};

int[] sub = Arrays.stream(x).filter(number -> number>= x[0]).toArray();

where stream() is converting array to a stream, filter is applying the required condition and then ending it with conversion into an Array again.

It is possible to filter the input array using Java 8 Stream API:

int[] x = {45, 8, 50, 15, 65, 109, 2};
int[] sub = Arrays.stream(x)
                  .filter(n -> n >= x[0])
                  .toArray();

System.out.println(Arrays.toString(sub));

Output:

[45, 50, 65, 109]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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