如何获得以下格式化输出?

编程入门 行业动态 更新时间:2024-10-15 22:25:25
本文介绍了如何获得以下格式化输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我编写代码以获得以下格式化输出,但是当我输入两位数的行数时,输出格式会发生变化.为什么?我该如何解决这个问题?

I wrote the code to get the following formatted output, but when I enter number of rows in double digits, the output format changes. Why? How can I fix this?

1 1 2 1 1 2 3 2 1 1 2 3 4 3 2 1

这是我的代码:

import java.util.*; class PTri { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the no. of rows for which " + "triangle has to be constructed"); int numrow = sc.nextInt(); for (int i = 1; i <= numrow; i++) { for (int j = 1; j <= numrow - i; j++) { System.out.print(" "); } for (int k = 1; k < i * 2; k++) { System.out.print(Math.min(k, i * 2 - k) + " "); } System.out.println(); } } }

推荐答案

这是因为两位数的值会改变整个架构.集合会向右移动一个位置.所以你可以提出这样的条件.我在数字之间添加了一个额外的空格以提高可见性.

It's because the value in double digit will change the whole architecture.The set will shift to right one place. So you can put a condition like this. I have added one extra space between numbers to improve visibility.

import java.util.*; class PTri { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter the no. of rows for which " + "triangle has to be constructed"); int numrow = sc.nextInt(); for (int i = 1; i <= numrow; i++) { for (int j = 1; j <= (numrow - i); j++) { System.out.print(" "); } for (int k = 1; k < i * 2; k++) { int temp = Math.min(k, i * 2 - k); if (temp > 9) { System.out.print(temp + " "); } else { System.out.print(temp + " "); } } System.out.println(); } } }

更多推荐

如何获得以下格式化输出?

本文发布于:2023-07-07 04:19:22,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1058700.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何获得

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!