简体   繁体   中英

How to print a descending/ascending number of spaces in Java?

I'm trying to print a figure that prints 3 spaces then a star, then the next line prints 2 spaces, / and a star, and then 1 space, // and a star and so on. I've got the code to print all the slashes and stars, but I can't figure out how to get the spaces to print with a descending number. This is for an assignment and I have to use nested for loops. Any thoughts? PS I don't want an exact answer (ie "type in this code"), I just want a suggestion to try to point me in the right direction.

What I have so far is (H is the scale):

public class Pattern { //program that prints a boxed-in design
  public static final int H = 9;
  public static void main(String[] args) {
    line();
    design();
  }
  public static void line() {
    System.out.print("+");
    for (int d=1; d <=H-2; d++) {
      System.out.print("-");
    }
    System.out.println("+");
  }
  public static void design() {
    top();
  }
  public static void top() {
    for (int row = 1; row <=H-2; row++){
      System.out.print("|");
      for (int sp =3; sp>=1; sp--){
        System.out.print(" ");
      }
      for (int fsl=1; fsl<=row-1; fsl++){
        System.out.print("/");
      }
      for (int star=1; star<=1; star++){
        System.out.print("*");
      }
      for (int bsl=1; bsl<=row-1; bsl++){
        System.out.print("\\");
      }
      System.out.print("|");
      System.out.println();
    }
  }
}

So if I understand correctly, your row variable goes from 1 through 4, and you want 3 spaces in row 1, 2 spaces in row 2, 1 space in row 3 and 0 spaces in row 4? I suggest you should be able to find an arithmetic expression (like you have already found row-1 for the number of slashes) to give you the correct number of spaces on each line/row. If I need to say more, feel free to add a comment to this answer.

package com.acme; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Comparator.reverseOrder; public class PrintIt { public static void main(String[] args) { printSpacesWithStar(10, Order.ASC); printSpacesWithStar(10, Order.DESC); } private static void printSpacesWithStar(int numbers, Order order) { Stream<Integer> streamOfInt = IntStream.rangeClosed(1, numbers) .boxed(); switch (order) { case ASC: streamOfInt .sorted(reverseOrder()) .forEach(Test::printingLogic); break; case DESC: streamOfInt .forEach(Test::printingLogic); break; } } private static void printingLogic(Integer currentValue) { for (int k = 1; k < currentValue; k++) { System.out.print(" "); } System.out.println("*"); } enum Order { ASC, DESC; } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM