Code doesn't execute properly
What the code is supposed to do is if the user does not enter an odd number it asks to do it again. Then if an odd number is entered it creates a diamond pattern.
Right now If I enter an even number, it asks to enter an odd number, but it doesn't allow me to do it. If I enter an odd number first, then the code executes properly.
I'm aware that the code is kind of sloppy as I am new to coding.
Code :
import java.io.*;
import java.util.Scanner;
public class Diamond {
public static void main(String [] args) throws IOException {
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String input;
int num;
System.out.println("input number: ");
input = stdin.readLine ();
num = Integer.parseInt(input);
if (num % 2 ==1){
int d = num;
int e = 0;
for (int a = 0; a <= num; a++) {
for (int c = d; c>= 1; c-- )
System.out.print(" ");
d-=1;
for (int b = 1; b <= a; b++)
System.out.print ("* ");
System.out.println();
}
num-=1;
for (int a = 0; a<=num; a++) {
for (int b = num; b > a; b--)
System.out.print (" *");
System.out.println();
for (int c = 0; c <= e; c++)
System.out.print(" ");
e+=1;
}}else
{System.out.println("Please enter an odd number!");
}
}
}
Re: Code doesn't execute properly
The reason for this is that you never state that the program should. Look in your else method. It says "System.out.println(....); " and then nothing else :P
One way to do it is to wrap the method in a while(true) loop, and in the first if statement, at the end put break; . like this:
Code :
import java.io.*;
import java.util.Scanner;
public class Diamond {
public static void main(String [] args) throws IOException {
System.out.println("input number: ");
while(true)
{
BufferedReader stdin = new BufferedReader (new InputStreamReader (System.in));
String input;
int num;
input = stdin.readLine ();
num = Integer.parseInt(input);
if (num % 2 ==1){
int d = num;
int e = 0;
for (int a = 0; a <= num; a++) {
for (int c = d; c>= 1; c-- )
System.out.print(" ");
d-=1;
for (int b = 1; b <= a; b++)
System.out.print ("* ");
System.out.println();
}
num-=1;
for (int a = 0; a<=num; a++) {
for (int b = num; b > a; b--)
System.out.print (" *");
System.out.println();
for (int c = 0; c <= e; c++)
System.out.print(" ");
e+=1;
}
break;
}else
{System.out.println("Please enter an odd number!");
}
}
}
}
Note that it prints "input number" before the while loop starts so that it doesn't repeatedly print it.