I am facing a problem with java array loops well, this is the problem
Use the space below to write main method that reads 5 integer values into an array named list. Then, use the array to output the positive values followed by the negative values and ignore zeros.
Sample Output
Enter 5 numbers: 10 -3 0 -4 9
List:
10
9
-3
-4
and this is the answer:
int [] list = new int[5];
// 1pt
Scanner read = new Scanner (System.in);
// 3pts
System.out.println("Enter 5 numbers:");
for (int i = 0; i < list.length; i++)
list[i] = read.nextInt();
// 3 pts
for (int i = 0; i < list.length; i++)
if (list[i] > 0)
System.out.println(list[i]);
// 3 pts
for(int i = 0; i < list.length; i++)
if (list[i] < 0)
System.out.println(list[i]);
but i do not know how to make them work together if you get me
The easiest way to do using Java8 can be this
Integer [] list = new Integer[5];
Scanner read = new Scanner (System.in);
System.out.println("Enter 5 numbers:");
for(int i=0; i<list.length;i++)
list[i] = read.nextInt();
List<Integer> newList = Arrays.asList(list).stream().filter(x -> x !=0).collect(Collectors.toList());
Collections.sort(newList,(a,b) -> {
if(a>b)
return -1;
else if(b>a)
return 1;
else
return 0;
});
System.out.println(newList);
You can use Stream filter() in java to get elements according to your need here we will check that value is not equal to zero (s-> s != 0)
and here we are using lambdas in java 8.
int [] list = new int[5];
Scanner read = new Scanner (System.in);
System.out.println("Enter 5 numbers:");
for (int i = 0; i < list.length; i++) {
list[i] = read.nextInt();
if(i == 4)
list = (Arrays.stream(list).filter(s -> s != 0).toArray());
}
System.out.println(Arrays.toString(list));
You can use the following code snippet to sort the array and then later display it and put a condition in between which checks whether an element of the array is 0
or not.
for(int i = 0 ; i <= 5 ; i++){
if(i < 5){
System.out.println("Enter 5 numbers:");
for (int i = 0; i < list.length; i++)
list[i] = read.nextInt();
continue;
}
for(int j = i ; i < 10 ; j++){
if(list[i] > list[j]){
int temp = list[i] ;
list[i] = list[j] ;
list[j] = temp ;
}
}
if(i == 5){
for(int j = 0; j < 5; j++){
if(list[i] != 0)
System.out.println(list[i]);
}
}
}
I guess this is what you want.
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.