java - 如何删除每行末尾的尾随空格?
问题描述
我正在 Dcoder 中尝试挑战,我的答案与预期的输出相同,但是我认为问题在于给定的情况,以删除每行末尾的尾随空格。
说清楚,这就是问题所在:
您需要将此模式打印到
N
,例如N = 3
预期输出:
1 1 2 1 2 3
不要在每行的末尾留下尾随空格!
这是我的代码:
String sp = " ";
for (int rows = 1; rows <= range; rows++) { //rows
for (int cols = 1; cols <= rows; cols++) {
System.out.print(Integer.toString(cols) + sp);
}
System.out.println(sp.trim());
}
我尝试连接Integer.toString(cols)
,sp
然后另一个sp.trim()
输出也相同,但挑战并没有说它是正确的,为什么会这样?任何人都可以解释或我的代码有问题吗?
解决方案
给你
int range = 3;
for(int rows = 1; rows <= range; rows++ ) {
for(int cols = 1; cols <= rows; cols++ ) {
if (cols == rows) {
System.out.println(Integer.toString(cols));
} else {
System.out.print(Integer.toString(cols) + " ");
}
}
}
推荐阅读
- angular - 检测 Angular 项目以覆盖量角器测试
- json - 如何解析 Dart 中的任何 json 文件?
- server - 尽管资源不是敏感数据,我是否应该将身份验证中间件添加到 GET 请求?
- linux - 如何获取排除某些子目录的路径列表
- python-3.x - SQLalchemy 查询不更新 put api 中的关系列
- python - MongoDB - 使用 update_many() 同时更新不同的数组
- angular - 使用导航的角度路由 - children 和 loadChildren 不能一起使用
- python - 使用 seaborn `displot` 自定义图例
- javascript - 图像和按钮按百分比放置,但在我调整窗口大小时被裁剪
- c# - 在 AWS 项目中使用来自不同来源的 NuGet 包