class Starr {
public static void main(String[] args) {
int res;
for(int i=1;i<=5;i++) {
for(int j=1;j<=5;j++) {
res=i+j;
if(res>=6) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
}
Output:
*
**
***
****
*****
Expected:
*
* *
* * *
* * * *
* * * * *
To get the above expected result i made the following changes,
{
System.out.print(" *"); /* Added a space before '*' */
}
else
{
System.out.print(" "); /* Added 2 spaces */
}
I would like to know if this expected result can be achieved in another logic where i don't have to change the print statement. Whatever changes i have done is a right approach?
You cannot achieve a way of printing whitespaces between the stars without printing anything, although you can achieve the desired output without using whitespaces. This could be done with System.out.format() or System.out.printf(). format and printf are actually the same thing in practice. For you particularly:
System.out.printf("%2s", "*");
This means that this output should print two characters, out of which the first one should be '*'. The rest will be whitespaces.
public class StarPattern {
public static void main(String[] args) {
// This loop print the number of * rows
for (int i = 5; i >= 1; i--) {
// This prints the empty space instead of *
for (int j = 1; j < i; j++) {
System.out.print(" ");
}
// Print the * in the desired position
for (int k = 5; k >= i; k--) {
System.out.print("*");
}
// Move the caret to the next line
System.out.println();
}
}
}
Output:
*
**
***
****
*****
Check this code, It works!
int res;
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
res = i + j;
String sp = (j != 1) ? " " : "";
if (res >= 6) {
System.out.print(sp + "*");
} else {
System.out.print(sp + " ");
}
}
System.out.println();
}
Output:
*
* *
* * *
* * * *
* * * * *
Related
I need to write a function that takes an array and prints '*' for each index by the value of the index
for example for 1,2,3,4 the output will look like this:
enter image description here
but my output is vertical
1
2
3
4
this is my printing code :
public static void printStars(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j <= a[i]; j++)
System.out.print("*");
System.out.println(" " + a[i]);
}
}
[edit] try the following:
public static void printStars(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >=0 ; i--) {
//String[] line = new String[a.length]; //this will keep allocating new memory
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j+1); //<change j+1 to a[j] in order to print out the value at each index of the array if you are not looking to print indexes
}else if (a[j] >= i) {
line[j] = "*";
}else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
it takes the maximum value in the array and stores in a variable. This is used to iterate each line. After that, it checks if at this current iteration, does an index of your array contain an asterisk in this location? if yes, assign asterisk to the specific index of the string array corresponding to index of original array, else assign whitespace.
Finally, when it goes to 0, you assign the either the values of your array or the indexes of the array to the string[]. Then you print the array by using String.join() with a delimiter of whitespace. This allows you to focus on white index contains a whitespace or not, and not need to focus on the formatting of whitespaces in between each item.
for the input [1,2,3,4] output is:
*
* *
* * *
* * * *
1 2 3 4
for the input [1,7,3,4]:
*
*
*
* *
* * *
* * *
* * * *
1 2 3 4
The solution from the previous answer works but I provided a slightly more compact version printStars and renamed the old one to printStarsOld. Here is the code:
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class IntTest {
public static void printStarsOld(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >= 0; i--) {
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j + 1);
} else if (a[j] >= i) {
line[j] = "*";
} else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
public static void printStars(int[] a) {
List<Integer> list = Arrays.stream(a).boxed().toList();
StringBuffer string = new StringBuffer();
Integer max = list.stream().max(Integer::compare).get();
for (int i = max; i > 0; i--) {
int finalI = i;
list.forEach(integer -> string.append(integer - finalI < 0 ? ' ' : '*').append(' '));
System.out.println(string.toString());
string.setLength(0);
}
for (Integer i=1; i<=list.size();i++) System.out.print(i.toString() + ' ');
}
#Test
public void test() {
System.out.println("Old output: ");
printStarsOld(new int[]{2, 4, 5, 1, 3});
System.out.println("New output: ");
printStars(new int[]{2, 4, 5, 1, 3});
}
}
The output is:
Old output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
New output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
Consider this code.
public static void patternMaker(int start, int max, int direction) {
if (start == 0) {
return;
}
for (int i = 0; i < start; i++) {
System.out.print("*");
}
System.out.println();
if (start == max) {
direction = -1;
}
patternMaker(start +direction, max, direction);
The output looks like this.
Where I need it to look like this
So I basically need the same thing but from the other side,and I need to move one space to the right and every new line.I am not sure how to produce that,I've tried duplicating the direction to get the other part of the X but that did not work out.Also not sure how to move one space to the right every line,I'd assume id need to adjust the direction on every iteration but missing a good idea.Thanks!
When using recursion is required, here is a solution based on your provided code example:
I outsourced the printing-part into a separate method.
public static void patternMaker(int max) {
patternMaker(1, max, 1);
}
public static void patternMaker(int numOfStars, int max, int direction) {
if (numOfStars == 0) {
return;
}
if (numOfStars == max) {
//print the maximum number of stars also before the middle
printPatternLine(numOfStars, max, false);
//print middle part twice
printPatternLine(numOfStars, max, true);
printPatternLine(numOfStars, max, true);
direction = -1;
}
printPatternLine(numOfStars, max, false);
patternMaker(numOfStars + direction, max, direction);
}
private static void printPatternLine(int numOfStars, int max, boolean middle) {
int spacesBefore;
int spacesBetween;
if(middle) {
spacesBefore = numOfStars;
spacesBetween = 0;
} else {
spacesBefore = numOfStars -1;
if(numOfStars == max) {
spacesBetween = 2;
} else {
spacesBetween = (max - numOfStars) * 4 + 2;
}
}
//print the spaces before the stars
for (int i = 0; i < spacesBefore; i++) {
System.out.print(" ");
}
//print first part of stars
for (int i = 0; i < numOfStars; i++) {
System.out.print("*");
}
//print spaces between the stars
for (int i = 0; i < spacesBetween; i++) {
System.out.print(" ");
}
//print second part of stars
for (int i = 0; i < numOfStars; i++) {
System.out.print("*");
}
//linebreak
System.out.println();
}
In the middle section of the X-drawing, the printPatternLine is called multiple times, to print this amount of stars a total of four times for this call of the patternMaker method.
A short explanation of the printPatternLine method:
The spaces before printing the stars and the spaces between the stars are calulated before
The case for the middle section should be self-explaining (no spaces between, spaces before equal to the number of stars)
For the non-middle part
The number of spaces before the stars relates to the position of the first stars for this line (for 1 * no space is printed, for 2 stars 1 space is printed, ...)
The number of spaces between the stars is 2 for the line which is one above the middle (1 space more on each side, 1 star more on each side). For every line that is one line farther away from the middle, the spaces in the middle increases by 4.
If you execute the patternMaker method with only one parameter by calling
patternMaker(3);
it will print this pattern:
* *
** **
*** ***
******
******
*** ***
** **
* *
If you need spaces between the stars, multiply the number of spaces by 2 in front of the for loops and add one space to the star-output like this:
private static void printPatternLine(int numOfStars, int max, boolean middle) {
//...
spacesBefore *= 2;
spacesBetween *= 2;
//...
for (int i = 0; i < numOfStars; i++) {
System.out.print("* ");
}
//...
for (int i = 0; i < numOfStars; i++) {
System.out.print("* ");
}
//...
}
Here is an example-output of patternMaker(3); with spaces:
* *
* * * *
* * * * * *
* * * * * *
* * * * * *
* * * * * *
* * * *
* *
Edit: An adaption, if the middle part should contain more stars than the line before and after it, is easily possible.
So I'm currently working on a personal project and I made a program that prints out star patterns. On one of the star patterns I want this output:
Figure
* *
** **
*** ***
**** ****
**********
So I made one method print out this:
Figure 1
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*" + " ");
}
System.out.println("");
}
*
**
***
****
*****
And another method print out this:
Figure 2
for (int i = 0; i < n; i++) {
for (int j = 2 * (n - i); j >= 0; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
*
**
***
****
*****
My question: How can I put the first method stars next to the other method stars?
This is what I got so far:
public static void printStarsVictory(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("*" + " ");
}
System.out.println("");
}
for (int i = 0; i < n; i++) {
for (int j = 2 * (n - i); j >= 0; j--) {
System.out.print(" ");
}
for (int j = 0; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}
This is what is printing so far:
*
**
***
****
*****
*
**
***
****
*****
Any idea how to solve this?
I think you are on the right track you just need to combine your two programs into the inner for loop:
private static void printStarsVictory(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j < n * 2; j++) {
if (j <= i || j >= (n * 2 - i)) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
System.out.println();
}
}
Example Usage printStarsVictory(5):
* *
** **
*** ***
**** ****
*********
Example Usage printStarsVictory(12):
* *
** **
*** ***
**** ****
***** *****
****** ******
******* *******
******** ********
********* *********
********** **********
*********** ***********
***********************
Each row has the increasing number of stars and decreasing number of spaces.
e.g. For n=5 first row has 2 stars at each side and 8 spaces.
At each iteration you can increase stars and decrease spaces and print them on the same line:
public static void printStarsVictory(int n) {
int sp = n * 2 - 2; // number of spaces
for (int i = 1; i <= n; i++) {
printStars(i); // print stars on the left side
int temp = sp;
while (temp > 0) {
System.out.print(" ");
temp--;
}
printStars(i); // // print stars on the right side
System.out.println("");
sp -= 2; // decrease spaces on each side
}
}
public static void printStars(int i) {
while(i>0) {
System.out.print("*");
i--;
}
}
Can you keep them in an array before printing to output:
public static void printStarsVictory(int n) {
StringBuilder[] lines = new StringBuilder[n + 1];
for (int i = 0; i < n; i++) {
lines[i] = new StringBuilder();
for (int j = 0; j <= i; j++) {
lines[i].append("*" + " ");
}
for (int j = 2 * (n - i - 1); j > 0; j--) {
lines[i].append(" ");
}
}
for (int i = 0; i < n; i++) {
for (int j = 2 * (n - i - 1); j > 0; j--) {
lines[i].append(" ");
}
for (int j = 0; j <= i; j++) {
lines[i].append("* ");
}
}
for (StringBuilder line : lines) {
System.out.println(line);
}
}
Well, System.out.println() prints only to the next row, not to the right. The only way is to create a new algorithm. You should put everything into single loop.
// loop starts from 0 and user counts from 1, so we wil decrement it by 1
n--;
// this loops moves pointer vertically
for (int i = 0; i < n; i++) {
// this loops moves pointer horisontally
for (int j = 0; j < n*2; j++) {
// here we choose what to print
if (j <= i || j >= n*2-i) {
System.out.print("*");
} else System.out.print(" ");
}
System.out.println();
}
You can visualize this figure as a matrix of numbers in a range: [-n, 0] inclusive vertically and [-n, n] inclusive horizontally, where each point is:
m[i][j] = Math.abs(i) - Math.abs(j);
If n = 4, then this matrix looks like this:
0 1 2 3 4 3 2 1 0
-1 0 1 2 3 2 1 0 -1
-2 -1 0 1 2 1 0 -1 -2
-3 -2 -1 0 1 0 -1 -2 -3
-4 -3 -2 -1 0 -1 -2 -3 -4
Try it online!
int n = 4;
IntStream.rangeClosed(-n, 0)
.map(Math::abs)
.peek(i -> IntStream.rangeClosed(-n, n)
.map(Math::abs)
.mapToObj(j -> i > j ? " " : "* ")
.forEach(System.out::print))
.forEach(i -> System.out.println());
Output:
* *
* * * *
* * * * * *
* * * * * * * *
* * * * * * * * *
See also: Making an hourglass using asterisks in java
Similar to this previous answer, you can use two nested for loops and one if else statement in the same way:
public static void main(String[] args) {
int n = 9;
for (int i = -n; i <= 0; i++) {
for (int j = -n; j <= n; j++)
if (Math.abs(i) <= Math.abs(j)
// in chessboard order
&& (i + j) % 2 == 0
// vertical borders
|| Math.abs(j) == n)
System.out.print("*");
else
System.out.print(" ");
System.out.println();
}
}
Output:
* *
** **
* * * *
** * * **
* * * * * *
** * * * * **
* * * * * * * *
** * * * * * * **
* * * * * * * * * *
** * * * * * * * **
See also:
• How to print a given diamond pattern in Java?
• Empty diamond shape with numbers
public class Hello {
public static void pattern() {
int s1 = 3;
while(s1 >= 1) {
System.out.println("*");
s1--;
}
}
public static void main(String [] args){
pattern();
}
}
Actual output:
*
*
*
Expected output:
* * *
* *
*
I would like to print " * " (like the above-expected output) using while loop. I made a while loop controlling the number of columns. I'm not able to make a while loop to control the rows to output "*" in the same line 3 times (next line 2 times and so on).
With just you one loop and some String.repeat() you can draw your pattern
Repeat the leading space, starting and 0, and one more each round
Repeat the pattern depending ong s1, 3 times, then 2 then 1
public static void pattern() {
int s1 = 3;
int s2 = 0; // space counter
while(s1 >= 1) {
System.out.print(" ".repeat(s2));
System.out.println("* ".repeat(s1).trim()); // trim to remove last space
s1--;
s2++;
}
}
int lines = 0, asterisks = 3;
String whiteSpace = "";
while (lines++ < 3) {
System.out.print(whiteSpace);
for (int i = 0; i < 3; i++) {
if (i <= (asterisks - lines)) {
System.out.print("* ");
}
}
whiteSpace += " ";
System.out.println();
}
My goal is to get this output when input is 3:
* *
* *
* *
*
* *
* *
* *
Here is my code:
public static void PrintX (int number) {
for (int i = 0; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
My output when input is 3 is like this and I'm not sure why there is the extra star at the top.
*
* *
* *
* *
*
* *
* *
* *
Your outer loop would work as you expect if you set an initial i value of 1. However, you could also make this a little shorter. First, consider storing the number * 2 + 1. Then you might combine a few lambda expressions with IntStream. Basically, you want to map each possible index to a " " or a "*" - so
public static void PrintX(int number) {
int len = number * 2 + 1;
IntStream.rangeClosed(1, len).forEachOrdered(i -> {
IntStream.rangeClosed(0, len)
.mapToObj(j -> i == j || i + j == len + 1 ? "*" : " ")
.forEachOrdered(System.out::print);
System.out.println();
});
}
Set i = 1 inside outer for loop. Compile and run the example below:
public class TestPrintX {
public static void PrintX (int number) {
for (int i = 1; i <= (number * 2 + 1); i++)
{
for (int j = 0; j <= (number * 2 + 1); j++)
{
if (i == j)
{
System.out.print("*");
}
else if (i + j == (number * 2 + 2))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}
System.out.println("");
}
}
public static void main(String arg[]) {
PrintX(3);
} // end of main method
} // end of class