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(" ");
}
}
}
}
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.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With