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
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
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
Currently working on some extra problem sets and seem to be stuck with this one. I need to make the following output:
* *
* *
* * * * *
* *
* *
I've got the cross down but i'm having problems with the middle line and was hoping someone could help me figure it out. Heres my code so far (input is set to 5):
public static void drawPlusVersion3(int input){
if (input % 2 != 0) {
for(int c = 0; c < input; c++) {
for(int r = 0; r < input; r++) {
if((c == input / 2) || (r == input / 2))
System.out.print("*");
if ( c == r){
System.out.print("*");
}
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}
Current output:
* *
* *
* * ** * *
* *
* *
Thanks in advance!
You can try:
public static void drawPlusVersion3(int input){
if (input % 2 != 0) {
for(int c = 0; c < input; c++) {
for(int r = input - 1; r >= 0; r--) {
if((c == input / 2) || (r == input / 2) || c == r)
System.out.print("*");
else
System.out.print(" ");
System.out.print(" ");
}
System.out.println();
}
}
}
How about this:
for (int i = 0; i < input; i++) {
for (int j = 0; j < input; j++) {
if (j == input / 2 || i == input / 2 || i + j == input - 1) {
System.out.print("* ");
} else {
System.out.print(" ");
}
}
System.out.println();
}
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:
*
* *
* * *
* * * *
* * * * *
I managed to get the result if I enter the base and exponent, but the output should be
For example: the output should look like this
>>base:5 exponent: 2
5^2 = 25
5^1 = 5
I need help to put something somewhere to make this happen...
import java.util.Scanner;
public class recursion {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);
int base = 0;
int expo = 0;
System.out.print("Enter number for base ");
for (int i = 0; i < 1; i++)
base = scanner.nextInt();
System.out.print("Enter number for exponent ");
for (int j = 0; j < 1; j++)
expo = scanner.nextInt();
System.out.println(base + "^" +expo +" = " + pow(base,expo));
}
public static int pow(int x, int p) {
System.out.println(x + "^" +p +" = " );
if (p == 0)
return 1;
if (p % 2 == 0) {
int a = pow(x, (p / 2));
return a * a; // This line
} else {
int a = pow(x, ((p - 1) / 2));
return x * a * a; // This line
}
}
}
Firstly, the following code snippets demands a review:
{
for (int i = 0; i < 1; i++)
/*
* This for loop is unnecessary.
* It asserts that the following clause is run only once,
* which is true for any statements anyway.
*/
// ...
}
return a * a;
} /* if (p % 2 == 0) */ else {
/*
* Statements are unnecessarily nested within else clause.
* The corresponding then clause does not complete normally.
* Moving the following code snippet out of an else block
* would have the same effect, but simplifies the control
* statements.
*/
int a = pow(x, ((p - 1) / 2));
return x * a * a;
}
Within your pow() method, you have a System.out.println() method. You're calling it for debugging, but it's unnecessary as the process returns normally. As you're looking for printing the operations for exponent as "from user-specified exponent -> 1" ("in descending order"), use a loop to print your System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));:
do // New!
System.out.println(base + "^" + expo + " = " + TestClass.pow(base, expo));
while (expo-- > 1); // New!
} /* main( args ) */
and you can remove the debugging line in pow().
Example: (>> denotes STDIN)
Enter number for base >> 5
Enter number for exponent >> 2
5^2 = 25
5^1 = 5
Enter number for base >> 4
Enter number for exponent >> 5
4^5 = 1024
4^4 = 256
4^3 = 64
4^2 = 16
4^1 = 4
View a live code demo.
void power(int base, int exp){
//Use for loop to iterate through each exp down to 0
for(int i=exp; i>=0; i--){
int result= exponent(base,i);
System.out.println(base + "^" + i + "=" + result)//Will display result as 5^2=25
}
//Recursively computes the result of b^e.
int exponent(int b, int e){
if(e==0){//Base case occurs when e=0.
return (1);
}
return (b * exponent(b,e-1));
}