Incomplete output with while loop - java

I am supposed to give this output
* * * * *
* * * * *
* * * * * *
* * * * *
so on and so forth 5 itirations
but it only shows the first 2 output
here's my code
public class itiration {
public static void main( String args[]){
int counter1 = 1;
int counter2 = 1;
int counter3 = 1;
while(counter1<=5)
{
while(counter2<=5)
{
System.out.print("* ");
System.out.print(" ");
counter2++;
}
System.out.println();
while(counter3<=5)
{
System.out.print(" ");
System.out.print("* ");
counter3++;
}
System.out.println();
counter1++;
}
}
}
this is not a homework

Have you tried stepping through this program with a debugger?
HINT: After the outer loop executes its first iteration, what are the values of counter2 and counter3?

You need to reset counter2 and counter3 in the loop (after counter1++ for example), otherwise they'll stay at value 5 after the first run of the loop, and the inner loops will not run any more.

You're not resetting counter2 and counter3 for each iteration of the main loop.
Try this:
int counter1 = 1;
while(counter1<=5)
{
int counter2 = 1;
int counter3 = 1;

Related

how do i change my output from horizontal to vertical in java?

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

Drawing an X shape with using only asteriks and recursion

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.

how to print " * " n number of times using while loop?

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();
}

Need help making code for equilateral triangle in java work

For some reason only the odd numbered lines are spacing correctly. Can someone please explain this? Here is my code.
import java.util.Scanner;
public class Triangle {
public static void main(String args[]) {
int i, j, k1;
Scanner in = new Scanner(System.in);
System.out.println("Enter the length of the side of your equilateral triangle: ");
int side = in.nextInt();
System.out.println("Enter the character you want your triangle filled with: ");
char fill = in.next().charAt(0);
while (side<=0 || side>50){
System.out.print("Please enter a length between 1 and 50: ");
side = in.nextInt();
break;
}
for(i=1; i<=side;i++){
for (k1=0; k1 < (side-i/2);k1++){
System.out.print("\t");
}
for(j=1;j<=i;j++){
System.out.print(fill + "\t");
}
System.out.println('\n');
}
in.close();
}
}
This is my outcome:
Enter the length of the side of your equilateral triangle:
5
Enter the character you want your triangle filled with:
*
*
* *
* * *
* * * *
* * * * *
I want this:
#
# #
# # #
# # # #
# # # # #
Just add this and change /t to 4 spaces:
if(i%2 ==0 && j ==1){
System.out.print(" "); // two spaces
}
Full code
for(i=1; i<=side;i++){
for (k1=0; k1 < (side-i/2);k1++){
System.out.print(" ");
}
for(j=1;j<=i;j++){
if(i%2 ==0 && j ==1){
System.out.print(" ");
}
System.out.print(fill + " ");
}
System.out.println('\n');
}
The reason is because every even line needs to start with a little offset since it has to be in the middle of the filler character and i get this
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
You haven't stated the desired outcome, but remove the /2 might do the trick.
Maybe replace both \t with a space.
Remove the '\n' from println, unless you want a blank line between lines.
How about this:
try (final Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8.name())) {
System.out.print("Enter the length of the side of your equilateral triangle: ");
final int side = scanner.nextInt();
System.out.print("Enter the character you want your triangle to be filled with: ");
final char character = scanner.next().charAt(0);
for (int i = 1; i <= side; i++) {
final StringBuilder builder = new StringBuilder(side);
for (int k = 0; k < (side - i); k++) {
builder.append(' ');
}
System.out.printf(builder.toString());
for (int j = 0; j < i; j++) {
System.out.printf("%s ", character);
}
System.out.println();
}
}
Please notice the try-with-resources with Scanner — only available in from Java 7 (and onwards).

What logic needs to be changed to get the star pattern

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:
*
* *
* * *
* * * *
* * * * *

Categories