Crash for a loop in Java

How I really like programming, and I like programming in my free time, so I tried to create code in which the output would look like x. Something like that.

x    x
 x  x
  x
 x  x
x    x

So, I wanted the user to enter the height "x". This is the code that I have, and I really don't know how to move on. I just need a hint, or can someone tell me where I was wrong.

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(" ");
      }
    }
  }
}
+5
source share
3 answers

Two changes:

  • change System.out.println("x");to System.out.print("x");(remove ln after printing)

  • after two lines

        System.out.print(" ");
    }
    

    add

    System.out.println();
    
+5
source
 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();
 }
0
source

This works for me for both odd and height 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
    }
  }
}
0
source

All Articles