I'm trying to change the following code so I get this output for radius 2:
*****
*** ***
** **
*** ***
*****
Any help will be appreciated as I'm about to go crazy!
public class Main {
public static void main(String[] args) {
// dist represents distance to the center
double dist;
double radius = 2;
// for horizontal movement
for (int i = 0; i <= 2 * radius; i++) {
// for vertical movement
for (int j = 0; j <= 2 * radius; j++) {
dist = Math.sqrt(
(i - radius) * (i - radius) +
(j - radius) * (j - radius));
// dist should be in the range (radius - 0.5)
// and (radius + 0.5) to print stars(*)
if (dist > radius - 0.5 && dist < radius + 0.5)
System.out.print("*");
else
System.out.print(" ");
}
System.out.println("");
}
}
}
The output looks oval because characters do not have same width and height. Think of an image that its pixels are not square, but vertical rectangles. I borrowed the c# version of the code linked by @Prasanth Rajendran, and made some modifications:
lineWidth
argumentxScale
argument, now every 1/xScale
characters in a row are equivalent to 1
data points// function to print circle pattern
static void printPattern(int radius, int lineWidth, double xScale)
{
double hUnitsPerChar = 1 / xScale;
double hChars = (2 * radius + lineWidth) / hUnitsPerChar;
double vChars = 2 * radius + lineWidth;
// dist represents distance to the center
double dist;
double lineWidth_2 = (double)lineWidth / 2;
double center = radius + lineWidth_2;
// for vertical movement
for (int j = 0; j <= vChars - 1; j++)
{
double y = j + 0.5;
// for horizontal movement
for (int i = 0; i <= hChars - 1; i++)
{
double x = (i + 0.5) * hUnitsPerChar;
dist = Math.Sqrt(
(x - center) * (x - center) +
(y - center) * (y - center));
// dist should be in the range
// (radius - lineWidth/2) and (radius + lineWidth/2)
// to print stars(*)
if (dist > radius - lineWidth_2 &&
dist < radius + lineWidth_2)
Console.Write("*");
else
Console.Write(" ");
}
Console.WriteLine("");
}
}
static void Main(string[] args)
{
printPattern(2, 1, 2);
printPattern(10, 3, 2);
}
Now the results are like this:
printPattern(2, 1, 2):
******
*** ***
** **
*** ***
******
printPattern(10, 3, 2):
**************
**********************
****************************
*********** ***********
******** ********
******** ********
******* *******
******* *******
****** ******
****** ******
****** ******
****** ******
****** ******
****** ******
****** ******
******* *******
******* *******
******** ********
******** ********
*********** ***********
****************************
**********************
**************
They look better in CMD:
Hope you can translate it to java.
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