【问题标题】:How to make a displaybox application that prompts user for length and width and then displays a box of asterisks如何制作一个显示框应用程序,提示用户输入长度和宽度,然后显示一个星号框
【发布时间】:2017-10-31 22:43:47
【问题描述】:

我想制作一个星号框,利用用户的长度和宽度,使用方法、参数和循环(如果可能的话,不要使用数组,因为我还没有学会它。)到目前为止我只显示一行星号,我不知道该怎么做。请帮忙!

    public static void drawBar(int length, String mark) {

    for (int i = 1; i < length; i++) {
        System.out.print(mark);
    }
}

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter a height: ");
    int length1 = input.nextInt();
    System.out.println("Enter a width: ");
    int length2 = input.nextInt();

    for (int j = 1; j < length1; j ++) {
        drawBar(j, "*");
    }

}

}

【问题讨论】:

  • 你需要第二个循环来管理高度,它环绕着写行的循环
  • @madprogrammer 他已经有两个相互包裹的循环。代码的结构有点奇怪。 @Zaki:您的长度变量范围不正确。您将j 传递给drawBar 而不是length2。我认为如果您修复它,它将正常运行。您也可以将 drawBar 中的 for 循环直接放入您的第一个方法中。这将使您的代码更易于阅读和理解控制流
  • @MadProgrammer 我对 Java 相当了解,所以你能告诉我如何设置第二个循环来管理高度。
  • @MadProgrammer 我应该使用 while 语句而不是 for 语句吗?
  • 没关系,我明白了

标签: java methods parameters


【解决方案1】:

你可以使用这样的东西:

public static void main(String[] args) throws UIException {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter a height: ");
    int height = input.nextInt();
    System.out.println("Enter a width: ");
    int width = input.nextInt();

    String mark = "*";

    for (int i = 0; i < height; i++) {//Number of lines it will repeat the process
        System.out.println(new String(new char[width]).replace("\0", mark));// "\0" is nul character that will be replace the N number of times needed to fill the width.
    }
}

你也应该从 0 开始 for 循环,在编程语言中你总是从零开始计数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-17
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多