在Java中使用for循环的麻烦

时间:2013-04-26 17:17:38

标签: java loops for-loop

因为我非常喜欢编程,我喜欢在空闲时间编程,所以我试图创建一个输出看起来像x的代码。像这样的东西。

x    x
 x  x
  x
 x  x
x    x

所以我希望用户输入“x”的高度。这是我到目前为止的代码,我真的不知道如何继续前进。我只需要一个提示或者是否有人可以告诉我哪里出错了。

import java.util.Scanner;    
    public class x{
    public static void main(String[] args){
    Scanner kbd = new Scanner(System.in);
    int height;    
    System.out.print("Enter the height of the X:   " );             
    height = kbd.nextInt();
    for (int i = 1; i <= height; i++){                        
      for (int j = 1; j <= height; j++) {                            
        if(i ==j || j+i == height + 1)                               
            System.out.println("x");                            
        else                            
            System.out.print(" ");
      }
    }
  }
}

3 个答案:

答案 0 :(得分:5)

两个变化:

  • System.out.println("x");更改为System.out.print("x");(打印后删除ln)

  • 后两行

        System.out.print(" ");
    }
    

    添加

    System.out.println();
    

答案 1 :(得分:0)

 for (int i = 0; i < height; i++){                        
    for (int j = 0; j < height; j++) {                            
        if(i == j || j + i == height - 1)                               
            System.out.print("x");                            
        else                            
            System.out.print(" ");
    }
    System.out.println();
 }

答案 2 :(得分:0)

对于X的奇数和偶数高度,这适用于我:

import java.util.Scanner;  
public class x{
    public static void main(String[] args){
    Scanner kbd = new Scanner(System.in);
    int height;    
    System.out.print("Enter the height of the X:   " );             
    height = kbd.nextInt();
    for (int i = 0; i <= height; i++){                        
      for (int j = 0; j <= height; j++) {                            
        if( (i ==j && i!=0 ) || j+i == height + 1) //needed to check for i or j !=0
            System.out.print("x"); //this shouldn't be println             
        else                            
            System.out.print(" ");
      }
      System.out.println(); //you needed this
    }
  }
}