java - 我的星号框程序无法正常工作

标签 java eclipse

所以我应该制作一个程序,用星号创建一个盒子,到目前为止它无法正确显示,有时列太小,有时太大,但从来没有达到它们需要的位置。有人可以帮忙吗!

import java.util.Scanner;

public class DisplayBox {

    public static void drawBar(int length){
        for (int i = 1; i <= length; i++){
            System.out.print("*");
        }

    }
    public static void drawHeight(int height, int length){
        int h = 0;
        while (h++ < length - 2){
            System.out.print("*");
            int h1 = 0;
            while (h1++ < length - 2){
                System.out.print("  ");
            }
            System.out.println(" *");

        }
    }

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("Please enter the length of the Box: ");
        int length = input.nextInt();
        System.out.println("Please enter the height!: ");
        int height = input.nextInt();
        System.out.println();
        drawBar(length);
        drawHeight(height, length);
        drawBar(length);
    }
}

最佳答案

  • 您在 drawBar 中没有 println 来结束该行
  • 您将 hlength 进行比较,而不是在 drawHeight 中比较 height

只是一个样式注释:如果您的方法生成给定长度的字符串,然后打印方法都在一个地方,可能会更清楚:

private String repeat(char ch, int len) {
    char chars = new char[len];
    Arrays.fill(chars, ch);
    return new String(chars);
}

println(repeat('*', length));
for (int l = 0; l < length - 2; l++)
    println("*" + repeat(' ', length - 2) + "*");
println(repeat('*', length));

关于java - 我的星号框程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37739355/

相关文章:

java - 无法获取 checkstyle 的类信息

java - 类路径条目 my.jar 未指向类路径引用的有效 jar

eclipse - 下载 eclipse 插件(无需安装)

java - Eclipse 问题 : the selection can not be launched, 并且最近没有启动

java - org.hibernate.MappingException : Could not determine type for: (foo)

java - 无法在 Eclipse Oxygen 中启动 Tomcat 服务器

Java 制作类的数组列表并调用该类的方法

java - 使用 RestTemplate 和 RestTemplateCustomizer 与多个服务的正确架构是什么?

eclipse - Tomcat 无法锁定日志文件

java - Eclipse 命令的键绑定(bind)