简体   繁体   中英

Creating a User-Input Asterisk Triangle using Java

I want to...

create an asterisk triangle , using Java, that matches the length of whatever number (Between 1-50) the user enters.

Details

  1. The first line would always start with an asterisk.
  2. The next line would increment by one asterisk until it matches the user's input.
  3. The following lines would then decrement until it is back to one asterisk.

For instance, if the user was to enter 3, then the output would have one asterisk on the first line, two asterisks on the second line, three asterisks on the third line, and then revert back to two asterisks on the following line before ending with an asterisk on the last line.

What I've tried so far

I am required to use nested for loops. So far, I tried to test it out using this practice example I made below. I was only able to create on output of the numbers. I also have some concepts of outputting asterisk triangles. How can I apply the concept of this code to follow along the user's input number?

 import java.util.Scanner;

public class Program
{
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        int count, index = 0, value, number;
        System.out.println("This program creates a pattern of numbers " );
        System.out.println("Based on a number you enter." );
            System.out.println("Please enter a positive integer. " );
        count = keyboard.nextInt();
        value = count;
        for (index = 1; index <= count; index++)
        {
            for (number = value; number >= 1; number--)
            {
                System.out.println(number);
            }
            value--;
            System.out.println();
        }
        }
}

Here's how i would proceed

  1. write a method printAsterisks that takes an int N as parameter and writes a line of N asterisks. You wil need a for loop to do so.
  2. call printAsterisks in a for loop that counts from 1 to COUNT
  3. call printAsterisks in a second loop that counts down from COUNT-1 to 1

That should do the trick.

Also, as a side note, you should close your scanner. The easy way to do so is enclose ot in a try-with-resource like so :

try (Scanner keyboard = new Scanner(System.in);) {
 // your code here
}

Let us know the version of the program taht works (or the question you still have) :)

HTH

Here is what you want:

public class Asterisk {
    private static final String ASTERISK = "*";
    private static final String SPACE = "";
    private static int LENGTH;

    public static void main(String[] args) {
        try{
            readLength();
            for (int i=1; i<=LENGTH; i++) {
                if (i == LENGTH) {
                    for (int j=LENGTH; j>=1; j--) {
                        drawLine(j);
                    }   
                    break;
                }
                drawLine(i);
            }
        }catch (Exception e) {
            System.out.println("You must enter a number between 1 and 50.");
        }
    }

    static void readLength(){
        System.out.println("Enter asterisk's length (1-50)");
        LENGTH = Integer.parseInt(System.console().readLine());
        if (LENGTH<=0 || LENGTH>50) 
            throw new NumberFormatException();
    }

    static void drawLine(int asterisks){
        StringBuilder line = new StringBuilder();
        int spacesLeft = getLeftSpaceCount(asterisks);
        int spacesRight = getRightSpaceCount(asterisks);

        for (int i=0; i<spacesLeft; i++) {
            line.append(SPACE);
        }

        for (int i=0; i<asterisks; i++) {
            line.append(ASTERISK);
        }

        for (int i=0; i<spacesRight; i++) {
            line.append(SPACE);
        }

        System.out.println(line.toString()+"\n");
    }

    static int getLeftSpaceCount(int asterisks){
        int spaces = LENGTH - asterisks;
        int mod = spaces%2;
        return spaces/2 + mod;  
    }

    static int getRightSpaceCount(int asterisks){
        int spaces = LENGTH - asterisks;
        return spaces/2;    
    }
}

I am required to use nested for loops

Yes, the main logic lies there...

for (int i=1; i<=LENGTH; i++) {
    if (i == LENGTH) {
        for (int j=LENGTH; j>=1; j--) {
            drawLine(j);
        }   
        break;
    }
    drawLine(i);
}

The triangle using 5 as input.

*

**

***

****

*****

****

***

**

*

Tip:

There is an easier way to get input from the user using System.console().readLine() .

In regards to the printing part, I wanted to clean up the answers a little:

int input = 3; //just an example, you can hook in user input I'm sure!
for (int i = 1; i < (input * 2); i++) {
    int amount = i > input ? i / 2 : i;
    for (int a = 0; a < amount; a++)
        System.out.print("*");
    }
    System.out.println();
}

For our loop conditions, a little explanation:

  • i < (input * 2) : since i starts at 1 we can consider a few cases. If we have an input of 1 we need 1 row. input 2, 3 rows. 4: 5 rows. In short the relation of length to row count is row count = (length * 2) - 1 , so I additionally offset by 1 by starting at 1 instead of 0.

  • i > input ? i / 2 : i i > input ? i / 2 : i : this is called a ternary statement, it's basically an if statement where you can get the value in the form boolean/if ? value_if_true : value_if_false boolean/if ? value_if_true : value_if_false . So if the row count is bigger than your requested length (more than halfway), the length gets divided by 2.

Additionally everything in that loop could be one line:

System.out.println(new String(new char[i > input ? i / 2 : i]).replace('\0', '*'));

And yeah, technically with a IntStream we could make this whole thing a one-line, though at that point I would be breaking out newlines for clarity

Keep in mind, I wouldn't call this the "beginner's solution", but hopefully it can intrigue you into learning about some other helpful little things about programming, for instance why it was I replaced \\0 in my one-line example.

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