所以我应该制作一个用星号创建一个盒子的程序,到目前为止它没有正确显示,有时列太小,有时太大,但从来没有它们需要的地方。有人可以帮忙!
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);
}
}
答案 0 :(得分:0)
println
中没有drawBar
来结束该行h
与length
进行比较,而不是height
drawHeight
进行比较
只是样式注释:如果您的方法生成给定长度的字符串然后打印方法都在一个地方可能会更清楚:
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));
答案 1 :(得分:0)
import java.util.Scanner;
public class DisplayBox {
public static void drawBar(int length){
for (int i = 1; i <= length; i++){
System.out.print("* ");
}
System.out.print("\n");
}
public static void drawHeight(int height, int length){
int h = 0;
while (h++ < length - 1){
System.out.print("*");
int h1 = 0;
while (h1++ < length-1){
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);
}
}
这似乎没问题..虽然