Search code examples
javastringsubstringjoptionpane

Outputting text as a half diamond


Assignment is to input text and then it prints out in the terminal as half a diamond. example:

T
 TE
  TEX
   TEXT
  TEX
 TE
T

I'm really close its just the last part. Here is my code:

import javax.swing.*;

// The "number 4" class.
public class number4
{
    public static void main (String[] args)
    {            
        String word = JOptionPane.showInputDialog ("Enter a word:");
        int len = word.length ();
        String SPACES = "                              ";       
        for (int i = 0 ; i < len; i++)
        {           
            System.out.print (word.substring (0,i) + System.lineSeparator());
            System.out.print(SPACES.substring(0,i));            
        }    
        String SPACES2 = "      ";          
        for (int g = len ; g>=0; g--)
        {           
            System.out.print (word.substring (0,g) + System.lineSeparator());  
            System.out.print(SPACES2.substring(g,g+1));              
        }        
        System.out.println();
    } // main method
} //number 4

The problem is at: System.out.print(SPACES.substring(g,g+1)); (the last part of the half diamond)

It currently looks like this:

T
 TE
  TEX
   TEXT
  TEX
  TE
  T

Solution

  • Fixed it. Here is new code: I just had to put the Spaces.substring before the word.substring in the for loops

    import javax.swing.*;
    
    // The "number 4" class.
    public class number4
    {
        public static void main (String[] args)
        {            
            String word = JOptionPane.showInputDialog ("Enter a word:");
            int len = word.length ();
            String SPACES = "                              ";       
            for (int i = 0 ; i < len; i++)
            { 
                System.out.print(SPACES.substring(0,i));            
                System.out.print (word.substring (0,i) + System.lineSeparator());           
            }            
            for (int g = len ; g>=0; g--)
            {          
                System.out.print(SPACES.substring(0,g));           
                System.out.print (word.substring (0,g) + System.lineSeparator());              
            }        
            System.out.println();
        } // main method
    } //number 4