将文本输出为半钻石

时间:2018-03-12 02:18:09

标签: java string substring joptionpane

作业是输入文字,然后在终端打印出半个钻石。例如:

T
 TE
  TEX
   TEXT
  TEX
 TE
T

我真的很接近它的最后一部分。这是我的代码:

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

问题出在:System.out.print(SPACES.substring(g,g+1));(半钻石的最后一部分)

目前看起来像这样:

T
 TE
  TEX
   TEXT
  TEX
  TE
  T

2 个答案:

答案 0 :(得分:2)

同样适用于Java。假设x = 'TEXT'len(x) = 4。我们将通过索引[0,1,...,6]。这与您编写for(int i = 0; i<2*len; i++)的情况相同。如果当前索引小于文本的长度,我们将增加间距,如果它更大,我们将减小间距。

for i in range(2*len(x)-1):
    if i < len(x): 
        y = ' '*i + x[0:i+1]
    else: 
        y = ' '*(2*len(x)-i-2) + x[0:len(x)-i-1]
    print(y)
  

T
TE
TEX
TEXT TEX
TE TE   

答案 1 :(得分:0)

修正了它。这是新代码: 我只需将Spaces.substring放在for循环中的word.substring之前

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