Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble with for loop in Java

As i really like Programming and i like to program in my free time so i was trying to create a code in which the output would look like an x. Something like this.

x    x
 x  x
  x
 x  x
x    x

So i wanted the user to input the height of the "x". This is the code i have so far and i really don't know how to move on. I just need a hint or if anyone can tell me where i went 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(" ");
      }
    }
  }
}
like image 225
akif Avatar asked Apr 26 '13 17:04

akif


People also ask

What are the 3 types of loops in Java?

Java provides three types of Loops: for, while, and do-while. Four Elements control a loop: initialization expression(s), test expression, update expression, and loop-body.

Can I put try catch inside for loop?

One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception. If you have try catch within the loop it gets executed completely inspite of exceptions.


1 Answers

Two changes:

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

  • after the two lines

        System.out.print(" ");
    }
    

    add

    System.out.println();
    
like image 123
Daniel S. Avatar answered Sep 30 '22 19:09

Daniel S.