# java - 如何在数组范围内查找数字

``````public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};

public AgeCount(){

}
public static int inRange(int b,int e)
{
int store[]=new int[a.length];
int count=0;
for (int i = 0; i < a.length; i  ) {
if(a[i]>b && a[i]<e)
{
return a[i];
}

}
return 0;
}
``````

#### 8 个答案:

``````public static void inRange(int b,int e)
{
int count=0;
System.out.print('{');
boolean first = true;
for (int i = 0; i < a.length; i  ) {
if(a[i]>=b && a[i]<=e)
{
if (!first) {
System.out.print(',');
} else {
first = false;
}
System.out.print(a[i]);
}

}
System.out.print('}');
}
``````

``````public class AgeCount {
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};

public AgeCount(){

}
public static void inRange(int b,int e)
{
ArrayList<Integer> store = new ArrayList<Integer>();
int count=0;
for (int i = 0; i < a.length; i  ) {
if(a[i]>=b && a[i]<=e)
{
store.append(a[i]);
}

}
println(store);
}
}
``````

Java 8方法：

``````int[] arr = new int[] {1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};
int res[] = Arrays.stream(arr).filter(n -> n  >= b && n <= e).toArray();
System.out.println(Arrays.toString(res));
``````

Java8：

``````public static void main(String[] args) {
int[] arrayToFilter = new int[]{1, 2, 45, 6, 3, 2, 1, 2, 5, 6, 65, 45, 43, 21, 34, 34};

int upperLimit = 5;
inRange(arrayToFilter, upperLimit);
}

private static void inRange(int[] arrayToFilter, int upperLimit) {
String sortedAndLimitedString = Arrays.stream(arrayToFilter)
.sorted()
.filter(value -> value < upperLimit)
.mapToObj(String::valueOf)
.collect(Collectors.joining(",", "{", "}"));

System.out.println(sortedAndLimitedString);
}
``````

``````   public static int[] inRange(int b,int e) {
return IntStream.of(a)
.filter(n -> n > b && n < e)
.sorted()
.toArray();
}

System.out.println(Arrays.toString(AgeCount.inRange(1, 6)));
// -> [2, 2, 2, 3, 5]
``````

```

``````import java.util.*;

public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};

public AgeCount()
{
}
public static void inRange(int b,int e)
{
int store[]=new int[a.length];
Arrays.sort(a);
for (int i = b; i < e; i  )
{
System.out.print(a[i 1] ",");
}
}
}
``````

``````//sort an array, get a defined index values, and print it on the screen.

import java.util.*;

public class AgeCount
{
static int[] a=new int[]{1,2,45,6,3,2,1,2,5,6,65,45,43,21,34,34};

public AgeCount()
{
}
public static int[] inRange(int b,int e)
{
int store[]=new int[a.length];
int[] myRange = new int[e-b];

Arrays.sort(a);

for (int i = b; i < e; i  )
{
for (int j = 0; j < (e-b); j  )
{
myRange[j] = a[i 1];
}
System.out.print(a[i 1] ",");
}
return myRange;
}
}
``````

0条回复