java - 如何在 Java 中显示数组中的某些数字?
问题描述
我想在一行中只挑出正数,在一行中只挑出负数,但它们只与文本一一显示。这是我的代码:
int[] array = {2, -5, 4, 12, 54, -2, -50, 150};
Arrays.sort(array);
for (int i = 0; i < array.length; i++) {
if (array[i] < 0) {
System.out.println("Less than 0: " + array[i]);
} else if (array[i] > 0) {
System.out.println("Greater than 0: " + array[i]);
}
}
解决方案
您当前正在为每个元素打印一行(以及它是否小于 0 或大于 0),而不是我将使用 anIntStream
和filter()
it 用于所需的元素(并使用 收集那些Collectors.joining()
)。喜欢,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
System.out.println("Less than 0: " + IntStream.of(array) //
.filter(x -> x < 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
System.out.println("Greater than 0: " + IntStream.of(array) //
.filter(x -> x > 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
输出
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
您可以使用一对StringJoiner
(s)for-each
循环和(仅仅因为)格式化 io 来获得相同的结果。喜欢,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
StringJoiner sjLess = new StringJoiner(", ");
StringJoiner sjGreater = new StringJoiner(", ");
for (int x : array) {
if (x < 0) {
sjLess.add(String.valueOf(x));
} else if (x > 0) {
sjGreater.add(String.valueOf(x));
}
}
System.out.printf("Less than 0: %s%n", sjLess.toString());
System.out.printf("Greater than 0: %s%n", sjGreater.toString());
推荐阅读
- if-statement - 结合 IF 公式
- json - 为什么初始 JSON 对象可解析,但其中的对象不可解析?
- c# - 在 WPF 中的选项卡项内动态添加用户控件
- java - 依赖于配置文件特定属性的 Spring Boot 属性
- php - 如何通过 odbc_connect() 从另一台计算机连接到 Microsoft Access 数据库?
- angular - 如何制作一个在单击时在 div 之间切换的按钮?
- android - 父布局无法检测到点击 WebView
- c# - 实现个人用户帐户和 Azure AD 身份验证
- java - @onetomany 和 @manytoone 联合表,同时让所有数据一次又一次地重复同一个父表 SpringBoot
- arm - Eigen NEON 后端是否经过优化以利用从 ARM A76 开始存在的 2x128b NEON 执行单元?