Я не могу обернуть голову вокруг программы "рисовать какую-то лестницу с мужчинами"
Вероятно, вы видели это раньше в классе Java 1: это проблема, которая просит вас написать программу, которая рисует следующий рисунок:
![enter image description here]()
Мне нужно использовать константу. Мне не разрешено использовать ничего, кроме for-loops, print
и println
. Нет параметров, нет массивов. Я знаю, как это сделать с параметрами и массивами, мне повезло. Любая помощь приветствуется!
Вот мой неполный код:
public class Stairs {
public static final int LENGTH=5;
public static void main(String[] args) {
printStairs();
}
public static void printStairs() {
for (int allStairs=1; allStairs<=15; allStairs++) {
for (int spaces=1; spaces<=(-5*allStairs+30); spaces++) {
System.out.print(" ");
}
for (int stair = 1; stair <= 5; stair++) {
System.out.println(" o *******");
}
}
}
}
Ответы
Ответ 1
Это звучит как вопрос о домашнем задании, поэтому я не просто хочу дать вам ответ, но попытаюсь разбить его на шаги. Подумайте о том, что вы знаете:
1) Каждый stickman имеет такую форму:
o ******
/|\ *
/ \ *
2) Вы можете распечатать это с помощью следующего кода:
System.out.println(" o ******");
System.out.println(" /|\ * ");
System.out.println(" / \ * ");
3) Вы можете печатать несколько с помощью цикла:
for (int stair = 1; stair <= LENGTH; stair++) {
System.out.println(" o ******");
System.out.println(" /|\ * ");
System.out.println(" / \ * ");
}
Подумайте о том, какой результат это даст вам, и что нужно изменить. Поймите, что каждому патчмену нужно отделить определенную сумму. Выясните, как отложить их соответственно на основе значения stair
.
Ответ 2
Вы можете посмотреть на фигуру и заметить, что у каждого stickman есть 3 строки для каждой строки:
- Пространства, если необходимо, пропорциональны количеству stickmen
- Часть человека-палки - вы можете жестко скопировать этот
- Плоская поверхность 6
*
или одна *
, за которой следуют 5 пробелов
- Пространства, если необходимо, пропорциональны количеству stickmen
- A
*
И в конце последняя строка *
пропорциональна числу stickmen.
Ответ 3
Вот моя последняя заключительная попытка с использованием форматирования.
public static void main(String[] args) {
int steps = 5;
for (int x = 0; x < steps; x++) {
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " o ******"
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " /|\\ * "
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
System.out.format(((steps == (x + 1)) ? "" : ("%"
+ ((steps - x - 1) * 5) + "s"))
+ " / \\ * "
+ ((x == 0) ? "" : ("%" + (x * 5) + "s"))
+ "*\n", " ", " ");
}
for (int i = 0; i < (steps + 1) * 5 + 2; i++) {
System.out.print("*");
}
}
Вывод:
o *******
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
o ****** *
/|\ * *
/ \ * *
********************************
\ о /
Подход ниже также забавный (в зависимости от ваших предпочтений юмора), но не полное решение:
for (String s = " o ***** /|\\ * / \\ * "; s
.charAt(8) != '*'; s = s.substring(5, s.length() / 3) + " "
+ s.substring(s.length() / 3 + 5, 2 * s.length() / 3) + " "
+ s.substring(2 * s.length() / 3 + 5, s.length()) + " ") {
System.out.println(s.substring(0, s.length() / 3) + "*");
System.out
.println(s.substring(s.length() / 3, 2 * (s.length() / 3))
+ "*");
System.out.println(s.substring(2 * (s.length() / 3), s.length())
+ "*");
}
Выход:
o ******
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
o ***** *
/|\ * *
/ \ * *
Ответ 4
Существует рекурсивный блок с уменьшающимся пробелом. Рекурсия заканчивается на LEFT_SPACE == 0
Рекурсивный блок
LEFT_SPACE o ******RIGHT_SPACE*
LEFT_SPACE/|\ * RIGHT_SPACE*
LEFT_SPACE/ \ * RIGHT_SPACE*
Ответ 5
Вот несколько советов:
- Вы должны думать об этом по горизонтали.
- Ваша основная петля должна быть связана с количеством лестниц, потому что вы связаны количеством лестниц, которые вы должны нарисовать.
- Скорее всего, будет проще распечатать каждую строку отдельно, поэтому поймите всю информацию, необходимую для рисования каждой строки.
Ответ 6
Вот что я в конечном итоге закончил:
public class Stairs {
public static final int LENGTH=5;
// The 'main method' prints out all the stairs with the appropriate indentations.
public static void main(String[] args) {
// outer loop
for (int allStairs=0; allStairs<=4; allStairs++) {
// first nested loops print the heads and tops of steps
for (int spaces=1; spaces<=(-5*allStairs+20); spaces++) {
printSpace();
}
System.out.print(" o ******");
for (int backWall=0; backWall<allStairs*(LENGTH); backWall++) {
printSpace();
}
printStar();
// second nexted loops print the body and the backs of the stairs
for (int spaces = 1; spaces <= (-5 * allStairs + 20); spaces++) {
printSpace();
}
System.out.print(" /|\\ *");
for (int backWall=1; backWall<=LENGTH*(allStairs+1); backWall++) {
printSpace();
}
printStar();
// third nested loops print the legs and lower backs of stairs
for (int spaces = 1; spaces <= (-5 * allStairs + 20); spaces++) {
printSpace();
}
System.out.print(" / \\ *");
for (int backWall=1; backWall<=LENGTH*(allStairs+1); backWall++) {
printSpace();
}
printStar();
}
// this loop prints the very bottom line of stars
for (int lastLine=1; lastLine<=32; lastLine++) {
System.out.print("*");
}
System.out.println();
}
// printSpace() prints out a space
public static void printSpace() {
System.out.print(" ");
}
// printStar() prints out an asterisk
public static void printStar() {
System.out.println("*");
}
}
Ответ 7
Я сделал это несколько иначе. Следующий script будет работать с любым количеством лестниц. Я прокомментировал это, чтобы вы точно знали, что я делаю.
public class stairman {
//establishing class constants
public static final int STAIR_NUM = 5;
public static final int WIDTH = STAIR_NUM * 5;
public static void main(String[] args) {
//perform this loop for as many times as there are stairs
for (int i=1; i<=STAIR_NUM; i++) {
//calculating number of spaces before the top line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//printing top line of the stair
head();
//calculating the number of spaces after the top line of the stair
for(int y=1; y<=((i-1)*5); y++){
System.out.print(" ");
}
System.out.println("*");
//calculating the number of spaces before the 1st middle line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//print the first middle line of the stair
middle1();
//calculating the number of spaces after the 1st middle line of the stair
for (int y=1; y<=(i*5); y++){
System.out.print(" ");
}
System.out.println("*");
//calculating the number of spaces before the 2nd middle line of the stair
for (int x=1; x<=(WIDTH+(i*(-5))); x++) {
System.out.print(" ");
}
//printing the 2nd middle line of the stair
middle2();
//calculating the number of spaces after the 2nd middle line of the stair
for (int y=1; y<=(i*5); y++){
System.out.print(" ");
}
System.out.println("*");
}
//calculating the number of stars needed for the bottom of the stairs
for (int z=1; z<=(WIDTH+7); z++) {
System.out.print("*");
}
}
public static void head() {
System.out.print(" o ******");
}
public static void middle1() {
System.out.print(" /|\\ *");
}
public static void middle2() {
System.out.print(" / \\ *");
}
}
Ответ 8
Я тестировал вышеуказанный код, и он не работал у меня. Поэтому я пошел на это и использовал некоторые из своих идей.
public class DrawStairs {
public static final int HEIGHT= 5;
public static final int TOTALHEIGHT= HEIGHT*5;
public static void main(String[] args){
//Main Outer Loop
for(int i=1; i<=HEIGHT; i++){
//Loop for the spaces before, then print the head
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printTop();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
//Loop for the spaces before, then print the body
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printMiddle();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
//Loop for spaces before, then print the legs
for(int j=1; j<=TOTALHEIGHT+(i*(-5)); j++){
System.out.print(" ");
}
printBottom();
//Loop for spaces after, then print asterisk
for(int j=1; j<=(i-1)*5; j++){
System.out.print(" ");
}
System.out.println("*");
}
// for loop for printing the floor of asterisks
for(int i=1; i<= TOTALHEIGHT+7; i++){
System.out.print("*");
}
}
public static void printTop() {
System.out.print(" o ******");
}
public static void printMiddle() {
System.out.print(" /|\\ * ");
}
public static void printBottom() {
System.out.print(" / \\ * ");
}
}