java - 在 Java 中创建这种模式?(我的循环不工作)
问题描述
我正在尝试创建一个程序,该程序依赖于用户输入的 2 到 10 之间的整数。
如果用户输入了四个,这应该是输出:
****
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
****
我希望输入 4 以在第一行输出四颗星以形成水平边缘,然后是 4 星对角线。然后沿着垂直“边缘”四颗星,然后重复对角线和水平边缘。
所以我可以画出第一条线,最后一条和中间线,但我的对角线由于某种原因甚至不会显示空格!
****
**
**
**
**
* *
* *
* *
* *
**
**
**
**
****
这是我的代码(我是初学者,但我一直在尝试解决这个问题,我真的需要一些帮助):
int num = 0;
System.out.println("Enter a value between 2 and 10.");
num = keyNum.nextInt();
while (num < 2 || num > 10) {
System.out.println("Enter a valid number please.");
num = keyNum.nextInt();
}
for (int a = 0; a < num + 1; a++)
{
System.out.print(" ");
}
for (int b = 0; b < num; b++)
{
System.out.print("*");
}
for (int c = 0; c < num; c++)
{
System.out.println("");
for (int d = num; d < 1; d--)
{
System.out.print(" ");
}
System.out.print("*");
for (int e = (num * 3) - 2; e < num; e++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int f = 0; f < num; f++)
{
System.out.println("");
System.out.print("*");
for (int g = 0; g < num * 3; g++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int h = 0; h < num; h++)
{
System.out.println("");
for (int i = num; i < 1; i--)
{
System.out.print(" ");
}
System.out.print("*");
for (int j = (num * 3) - 2; j < num; j++)
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println("");
for (int k = 0; k < num + 1; k++)
{
System.out.print(" ");
}
for (int l = 0; l < num; l++)
{
System.out.print("*");
}
任何形式的帮助将不胜感激!谢谢你。
解决方案
这应该可以工作只是改变了几个for
循环条件
while (num < 2 || num > 10) {
System.out.println("Enter a valid number please.");
num = keyNum.nextInt();
}
for (int a = 0; a < num + 1; a++)
{
System.out.print(" ");
}
for (int b = 0; b < num; b++)
{
System.out.print("*");
}
for (int c = 0; c < num; c++)
{
System.out.println("");
for (int d = num; d > c; d--)
{
System.out.print(" ");
}
System.out.print("*");
for (int e = num * 2; e < (num * 3) + (c *2); e++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int f = 0; f < num; f++)
{
System.out.println("");
System.out.print("*");
for (int g = 0; g < num * 3; g++)
{
System.out.print(" ");
}
System.out.print("*");
}
for (int h = 1; h <= num; h++)
{
System.out.println("");
for (int i = 0; i < h; i++)
{
System.out.print(" ");
}
System.out.print("*");
for (int j = 0; j < (num * 3) - (h * 2) ; j++)
{
System.out.print(" ");
}
System.out.print("*");
}
System.out.println("");
for (int k = 0; k < num + 1; k++)
{
System.out.print(" ");
}
for (int l = 0; l < num; l++)
{
System.out.print("*");
}
推荐阅读
- innodb - innodb_flush_log_at_trx_commit 和 sync_binlog 有什么区别?
- reactjs - 我可以将状态值从一个组件导入到 react-Redux 中的另一个组件吗?
- javascript - 添加 angular-daterangepicker javascript 文件时出错
- jquery - 使用javascript函数启动mignific popup
- python - 将 Pandas 数据框从 Excel 文件 (xlrd) 转换为列表
- google-chrome-extension - 如何使用 Chrome DevTools 拦截跨扩展消息?
- android - 如何自动隐藏工具栏
- flutter - 从网址查看 pdf,无需通过 flutter_full_pdf_viewer 下载
- python-3.x - Numpy即使安装也无法导入
- java - 找出句子中元音最多的词(可以是几个最大的词,彼此等价)