使用java使用字符串和矩阵生成特定模式

时间:2015-04-14 15:32:40

标签: java string matrix

我需要在java中使用String和Matrix生成特定模式。用户应该能够从A-Z输入任何奇数位置字符。例如,如果用户选择G,则输出应为:

ABCDEFGFEDCBA
ABCDEF FEDCBA
ABCDE EDCBA
ABCD DCBA
ABC CBA
AB BA
A A


我尝试了以下代码:但我没有得到所需的输出:

    import java.io.IOException;
import java.util.Scanner;
public class PatternDemo3 
{
    public static void main(String[] args) throws IOException 
    {        
        Scanner in=new Scanner(System.in);
        System.out.println("Enter a odd positioned letter from A to Z to create the pattern : ");
        char input=(char)System.in.read();
        int val=(int)input;
        int newvalue=val-64;

        for (int i =newvalue; i >=0; i--) 
        {
            int begining=65;
            for (int j = 0; j < i; j++) 
            {
                System.out.print((char)begining);
                begining++;                
            }
            int newbeg=begining-1;            
            for(int k=0;k<(2*i-1);k++)
            {
                System.out.print(" ");
            }            
            for (int j = 0; j <i; j++) 
            {
                System.out.print((char)newbeg);
                newbeg--;                              
            }
            System.out.println("");            
        }        
    }    
}

1 个答案:

答案 0 :(得分:2)

这是编辑我收到的回复后的最终代码。

import java.io.IOException;
import java.util.Scanner;
public class PatternDemo3 
{
    public static void main(String[] args) throws IOException 
    {        
        Scanner in=new Scanner(System.in);
        System.out.println("Enter a odd positioned letter from A to Z to create the pattern : ");
        char input=(char)System.in.read();
        int val=(int)input;
        int newvalue=val-64;

        for (int i =newvalue; i >=0; i--) 
        {
            int begining=65;
            for (int j = 0; j < i; j++) 
            {
                System.out.print((char)begining);
                begining++;                
            }
            int newbeg=begining-1;            
            for(int k=1; k< 2 * (newvalue-i);k++)
            {
                System.out.print(" ");
            }            
            for (int j = 0; j <i; j++) 
            {
                if((char)newbeg!=input)
                {
                System.out.print((char)newbeg);
                }
                newbeg--;

            }
            System.out.println("");            
        }        
    }    
}