stuffandthings stuffandthings - 4 months ago 20
Java Question

Diamond Shape Based on Characters of String

I need to write a program that reads a string and then outputs a diamond shape based on the characters within the string (from user input). For example, if the user enters sample it should print the following in a diamond:
S
SAS
SAMAS
SAMPMAS
SAMPLPMAS
SAMPLELPMAS
SAMPLPMAS
SAMPMAS
SAMAS
SAS
S

I have figured out how to print the first letter of whatever the input is, do not know how to go about with the other letters. (This is for the normal triangle, I'm assuming the inverted one will be very similar.)

import java.util.Scanner;
public class PrintDiamond {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.println("Please enter a string");
String str = input.nextLine();
int l=str.length()*2-1;
int m=str.length();
for (int i=0; i<=m; i++) {
for (int j=0; j<=l; j++) {
if (j<=m-i) {
System.out.print(" ");
} else if (j==m) {
System.out.print(str.charAt(m-j));
} else if (j>=m+i) {
System.out.print(" ");
}
}
System.out.print("\n");
}
}

}

Answer

I would suggest using a Stringbuilder and a helper method to add the spaces necessary to keep a diamond shape.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter a string");
    String str = input.nextLine();
    StringBuilder sb;
    int i;
    for(i=1; i<=str.length(); i++){
        System.out.print(addSpace(str.length()-i) + str.substring(0,i));
        if(i>1){
            sb = new StringBuilder(str.substring(0,i-1));
            sb = sb.reverse();
            System.out.print(sb.toString())
        }
        System.out.println();
    }
    for(i=str.length()-1; i>0; i--){
        System.out.print(addSpace(str.length()-i) + str.substring(0,i));
        if(i>1){
            sb = new StringBuilder(str.substring(0,i-1));
            sb = sb.reverse();
            System.out.print(sb.toString())
        }
        System.out.println();
    }
}
public static String addSpace(int x){
    String s = "";
    for(int i=0; i<x; i++){
        s += " ";
    }
    return s;
}

Also something to consider: by simply reading the next line to use, you allow spaces. While this won't cause errors per say, it will contradict the idea of making a diamond shape.

Comments