【问题标题】:How to create an X pattern in Java given length and width from user?给定长度和宽度的用户如何在 Java 中创建 X 模式?
【发布时间】:2023-03-08 00:27:01
【问题描述】:

尝试编写一个程序,根据用户输入的宽度和长度生成一种 X/螺旋图案。长度是屏幕上有多少个字符,宽度是多少个字符高。 我无法找出数学关系来实现我想要的模式。

以下是正确的示例输出:
输入您想要的长度:39
输入您想要的宽度:7

这是我目前拥有的代码及其生成的代码:

import java.util.Scanner;

public class Twisty {
    public static void main(String[] args){
      Scanner myScanner = new Scanner(System.in);
      System.out.print("Input your desired length: ");
      int length = myScanner.nextInt();
      System.out.print("Input your desired width: ");
      int width = myScanner.nextInt();

      for(int i=0; i<width; i++) {
        for(int j=0; j<length; j++) {
            if(i==j || (i+j)%width==width-1 || (i+j)%width==0) {
                System.out.print("#");
            } else {
                System.out.print(" ");
            }
        }
        System.out.println();
     }
   }
}

输入你想要的长度:39
输入您想要的宽度:7

我究竟做错了什么?感谢您的帮助。

【问题讨论】:

  • 这里有一个问题:当长度 > 宽度时,你应该如何处理 X 的实际形状。因为在某些时候,您必须将多个 X 放在一起。根据长宽比的不同,可能会有很多变化。因此,您需要确定这些情况下的预期输出行为。

标签: java for-loop nested-loops


【解决方案1】:

专注于一个 X 开始。您应该只需要检查 2 个案例。一个绘制 X 的一部分,另一个绘制另一侧。我基本上是从您的代码中获取的,并删除了 if 语句中的第三个条件。

//System.out.print("Input your desired length: ");
int length = 7;
//System.out.print("Input your desired width: ");
int width = 7;

for(int i=0; i<width; i++){
    for(int j=0; j<length; j++){
        if(i==j  || (i+j)%width==width-1){
            System.out.print("#");
        }else{
            System.out.print(" ");
        }
    }System.out.println();
}

当你降低了这种行为并且你可以画一个 X 之后,你只需要修改你水平的宽度。用宽度修改长度位置几乎就像在画一个全新的 X .你可以这样做:

//System.out.print("Input your desired length: ");
int length = 39;
//System.out.print("Input your desired width: ");
int width = 7;

for(int i=0; i<width; i++){
    for(int j=0; j<length; j++){
        if(i==j%width  || (i+j%width)%width==width-1){
            System.out.print("#");
        }else{
            System.out.print(" ");
        }
    }System.out.println();
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2012-10-11
    • 2019-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    相关资源
    最近更新 更多