【问题标题】:How to print out an "X" in java that takes the height from the user and the character from the user如何在java中打印出一个“X”,它从用户那里获取高度和用户的字符
【发布时间】:2014-02-10 21:40:13
【问题描述】:

我需要创建一个方法,它采用整数“height”和 char 参数“c”,并使用“c”中的特殊字符打印出一个“X”,即“height”字符高。我的教授说它可以使用两个循环来完成,但我认为它需要的不止这些。

 public static void printX(int height, char c)
 {
     int i,j;
     int count=0; 

     for(i=0; i<height; i++)
     {
          count++; 
          for(j=0; j<count; j++)
          {
              System.out.print(" "); 
          }
          System.out.print(c);   
          System.out.println(); 
     }
 }

我开始编写只打印出一条对角线的代码,并试图看看我是否可以从那里弄清楚如何做到这一点,但我无法弄清楚。有没有办法用两个 for 循环来做到这一点?

【问题讨论】:

  • 提示:有两行:y = xy = height - x。如果您的ij 值解决了任一方程,则打印c,否则打印一个空格。
  • 如果您不在循环外使用ij,请在for-statement 中声明它们:for(int i = 0; i &lt; height; i++)

标签: java for-loop methods


【解决方案1】:

对于高度 = 7,您想要:

x     x
 x   x
  x x
   x
  x x
 x   x
x     x
  1. 第一行是0个空格,1个字符,5个空格,1个字符
  2. 第二行是1个空格,1个字符,3个空格,1个字符
  3. 第 3 行是 2 个空格,1 个字符,1 个空格,1 个字符

看到模式了吗?

中间线很特别。

其余部分遵循与顶部相同的模式,但相反。

【讨论】:

    【解决方案2】:

    这里我们考虑高度和 j=i 和 j=height-i

    public class printCross{
    
    public static void main (String[] arg){
    
        Scanner keyboard =new Scanner (System.in);
        System.out.println(" Please type a number grater than 2 :");
        int num=keyboard.nextInt();
        drawCross(num);
    
    }
    
    private static void drawCross(int num) {
    
    int startCur = 0; 
    int endCur = num-1; 
    for (int i = 0; i < num; i++) 
    { 
    for (int j = 0; j < num; j++) 
    { 
    if (startCur == endCur && j == i) 
    System.out.print('*'); 
    else if (startCur == j || endCur == j) 
    System.out.print('*'); 
    else 
    System.out.print(' '); 
    } 
    startCur++; 
    endCur--; 
    System.out.println(); 
    } 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      • 2014-01-10
      • 2010-10-05
      相关资源
      最近更新 更多