How to print star pattern in java - java

I tried to find any sequence or formula for below star pattern but i did not found, so simply tried below
public class MyClass {
public static void main(String args[]) {
System.out.println("....*....");
System.out.println("...***...");
System.out.println("*********");
System.out.println(".*******.");
System.out.println("*********");
System.out.println("...***...");
System.out.println("....*....");
}
}
Here "." means " " space character.
Can we print this star using loop ?

Not sure what you mean, but if you really want a loop, here is a solution!
public class Star {
public static void main(String[] args) {
int[] dots = new int[] {4, 3, 0, 1, 0, 3, 4};
int width= 9;
for (int i = 0; i < dots.length; i++) {
for (int j = 0; j < width; j++) {
if (j < dots[i] || j > width - dots[i] - 1) {
System.out.print(".");
} else {
System.out.print("*");
}
}
System.out.println();
}
}
}

Hope It Helps! This is Easy to understand for Low Class Students Rather than Creating Arrays
class starPattern {
public static void main(String []args) {
for(int i=1;i<=7;i++) {
for(int j=1;j<=9;j++) {
if(i==3 || i==5 || j==5 || (i==4 && j>1 && j<9) || ((i==2 || i==6) && (j>3 && j<7))) {
System.out.print("*");
}else{
System.out.print(" ");
}
}
System.out.println();
}
}
}
My Computer Teacher Check it and it was Correct Method!
A Brief Description About this Pattern
1↓ 1→ 2 3 4 5 6 7 8 9
2 *
3 * * *
4 * * * * * * * * *
5 * * * * * * *
6 * * * * * * * * *
7 * * *
8 *

I'm using Java 11. You should be able to draw any enantiomorphic pattern of asterisks. Read the comments for detailed explanation.
import java.util.Arrays;
class Star {
public static void main(String[] args) {
int[] stars = new int[] { 1, 3, 9, 7, 9, 3, 1 }; // asterisks per line
int max = Arrays.stream(stars).max().getAsInt(); // max asterisks in any line
for (int i = 0; i < stars.length; i++) { // prints the asterisks for a given row, and pads it left and right with spaces
System.out.print(" ".repeat((max - stars[i]) / 2) + "*".repeat(stars[i]) + " ".repeat((max - stars[i] + 1) / 2));
}
}

Yes, it can be done using loops and should not be done via sout statements.
Also seems like you are a beginner in programming, so I will suggest you to try out logic for these kind of questions yourself. It will help in your growth.
Just try out line by line.
These questions generally need 2 loops, one to move in vertical direction and other to move in horizontal direction.
You can think it of as a i*j matrix( eg 3X3, 4X4).
So try it out yourself start with some basic one's.
If you still need solution just ping me but please try it on your own first.

Related

I need some help diagnosing the problem with this code

I'm having trouble with some code. This code's purpose is just to take user-inputted numbers, append them to a string, and create a histogram representing the amount of numbers in each 5 number range from 1 to 50. Ex.
1 - 5: ***
6 - 10: ********
11 - 15: *
etc.
Here is the code:
public class Ch10Ex4 {
public static int number;
public static ArrayList<Integer> numbers = new ArrayList<>();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
getNums(1, 50);
}
histogram(1, 50, 5);
System.out.println();
}
public static void getNums(int low_num, int high_num) {
Scanner sc = new Scanner(System.in);
do {
System.out.print("Enter a number between " + low_num +
" and " + high_num + ": ");
number = sc.nextInt();
} while (number < 1 || number > 50);
System.out.println(number + " has been added sucsessfully.");
numbers.add(number);
}
public static void histogram(int low, int high, int range) {
int temp_low = low;
int temp_high = low + (range - 1);
for (int i = 0; i < high / range; i++) {
System.out.print("\n" + temp_low + " - " + temp_high + ": ");
for (int arr:numbers) {
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
}
temp_low += range;
temp_high += range;
}
}
}
I had a previous version of this code where I would call histogram() with two parameters. These would be the lowest number and the highest number like usual but no int range parameter. And I didn't have the outermost for-loop. I would have to call histogram 10 times ex.
histogram(1, 5);
histogram(6, 10);
histogram(11, 15);
etc.
Basically, I would call it for every set of five numbers. It worked but it was super inefficient and not very reusable. The problem is that when I run this code (entering numbers 1- 10), I get this:
1 - 5: **********
6 - 10: *****
11 - 15:
16 - 20:
etc.
The first set of five outputs an asterix for every number in the array.
Sorry for the incredibly long post. Any help is much appreciated and thank you in advance.
The bug is that you are using i in this if-statement.
if (arr >= temp_low && i <= temp_high) {
System.out.print("*");
} else {
}
Switch it to arr and you should be good.

Why won't my for loop be used in the output?

These mailboxes were numbered 1 through 150, and beginning with mailbox 2, he opened the doors of all the even-numbered mailboxes, leaving the others closed. Next, beginning with mailbox 3, he went to every third mail box, opening its door if it were closed, and closing it if it were open. Then he repeated this procedure with every fourth mailbox, then every fifth mailbox, and so on.
I am trying to recreate this paragraph. I know my first and third function are find but for some reason my boolean is not using my loop in my second function in the output. Here is the code:
public class Lab {
public static void main (String[] args) {
Boolean[] mailboxarray = new Boolean[150];
closeMailboxes(mailboxarray);
doCrazyMailman(mailboxarray);
showMailboxstate(mailboxarray);
}
/**
* purpose:
* pre-condition:
* post-condition:
* #param mailboxarray
*/
public static void closeMailboxes(Boolean[] mailboxarray) {
for (int i = 0; i <150; i++) {
mailboxarray[i] = Boolean.FALSE;
}
}
/**
* purpose:
* pre-condition:
* post-condition:
* #param mailboxarray
*/
public static void doCrazyMailman(Boolean[] mailboxarray) {
// to help you with troubleshooting, I will add some outputs
// it is always beneficial to be able to see what's your program
// is actually doing right now
for (int i = 1; i <= 150; i++) {
for (int j = i; j < 150;j=j+i+1) {
}
}
}
/**
* purpose:
* pre-condition:
* post-condition:
*/
public static void showMailboxstate(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
int number = i + 1;
// this will output only closed doors
// as shown in assignment's screenshot
// it reads next:
// if the current boolean is FALSE - display message
if (!mailboxarray[i])
System.out.println("Door " + number + " is closed");
}
}
}
Adapted your code to do the homework.
The catch is to look carefully at array indexes and know the use of negate boolean values.
class Lab {
public static void main(String[] args) {
Boolean[] mailboxarray = new Boolean[150];
closeMailboxes(mailboxarray);
doCrazyMailman(mailboxarray);
showMailboxstate(mailboxarray);
}
/**
* purpose: pre-condition: post-condition:
*
* #param mailboxarray
*/
public static void closeMailboxes(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
mailboxarray[i] = Boolean.FALSE;
}
}
/**
* purpose: pre-condition: post-condition:
*
* #param mailboxarray
*/
public static void doCrazyMailman(Boolean[] mailboxarray) {
// to help you with troubleshooting, I will add some outputs
// it is always beneficial to be able to see what's your program
// is actually doing right now
for (int i = 2; i <= 150; i++) {
for (int j = i; j <= 150; j = i + j) {
// switch open-close by negate
// work with real case counter and take care to modify at proper place in arr
mailboxarray[j - 1] = !mailboxarray[j - 1];
// System.out.println(i + ":" + j + ":" + !mailboxarray[j - 1] + ":" +
// mailboxarray[j - 1]);
}
}
}
/**
* purpose: pre-condition: post-condition:
*/
public static void showMailboxstate(Boolean[] mailboxarray) {
for (int i = 0; i < 150; i++) {
int number = i + 1;
// this will output only closed doors
// as shown in assignment's screenshot
// it reads next:
// if the current boolean is FALSE - display message
if (!mailboxarray[i])
System.out.println("Door " + number + " is closed");
}
}
}
output
Door 1 is closed
Door 4 is closed
Door 9 is closed
Door 16 is closed
Door 25 is closed
Door 36 is closed
Door 49 is closed
Door 64 is closed
Door 81 is closed
Door 100 is closed
Door 121 is closed
Door 144 is closed

Pyramid of pin using Recursion

I want to print a pyramid of pins using recursion(no Loops). I got the code almost done, but my pyramid is upside down, and it is not formatted. How can I fix it.
Below is my source code:
public void pinPattern(int count) {
if(count == 1)
System.out.println("*");
else {
System.out.print("*");
pinPattern(count - 1);
}
}
public int numberOfPins(int n) {
if(n == 0)
return 0;
else {
pinPattern(n);
return n + numberOfPins(n - 1);
}
}
public static void main(String[] args) {
Recursion x = new Recursion();
System.out.println("The number of pin: " + x.numberOfPins(5));
}
Thanks in advance.
So there are two considerations here. First, the need to have the pyramid go the other direction. If it is printing upside-down, then instead of counting down (which goes from max to min), invert the approach. Something like:
public static int pinPatternUp(int numPins, int maxPins)
{
if (numPins <= maxPins) {
// this will add spaces
spaces(maxPins - numPins);
pins(numPins);
return numPins + (pinPattern(numPins + 1, maxPins));
}
return 0;
}
The logic for the pins method (which in the OP's code was 'pinPattern) in the OP's approach is essentially fine for either direction. However, making this change (so that there is a space after each*`) will allow for a bit better formatting.
System.out.print("* ");
The second question is one of formatting. In this case, we can look at the pyramid as requiring N spaces before the first output. And with a bit of investigation, it appears that a given line will have the total number of rows - the current row in terms of spaces. Using recursion, it is possible to do something like:
public static void spaces(int num)
{
if (num == 0) {
return;
}
System.out.print(" ");
spaces(num - 1);
}
Note that one can now have an "up" or "down" facing pyramid depending upon whether the pinPattern is increasing or decreasing.
Note: due to some editing, the method names do not exactly align with the OP's.
public static void main(String[] args)
{
pinPatternUp(1, 5);
pinPatternDown(5, 5);
}
Output if run up and then down:
*
* *
* * *
* * * *
* * * * *
* * * * *
* * * *
* * *
* *
*

2 boolean check aren't compatible

Trying to create a method that will make an array and assign different numbers from 1 - 9 to each index of the array (nos. cannot be repeated).
please have a look at the boolean comparison i made, this is where the cmd stuck at runtime. I have tried to separate the two but nothing happens.
Please help.
import java.util.ArrayList;
class Testing {
public static void main (String[] args) {
ArrayList<Integer> grid = new ArrayList<Integer>();
int randNum;
int count = 0;
int size=8;
for (int b = 0; b <=size; b++) {
while (count <= size) {
randNum = (int) (Math.random() * 9);
if (grid.contains(randNum) == false & randNum != 0 ) {
grid.add(randNum);
count++;
}
}
System.out.println(grid.get(b));
}
System.out.println("size: " + grid.size());
}
}
Why not use a Fisher-Yates shuffle instead?
That is, fill the array with 1-9 and then Collections.shuffle() it.
Aside: use && not & in your original code.
I agree with Matt Ball, create an array 1-9 and shuffle, but to answer your question, the problem is here:
randNum = (int) (Math.random() * 9);
if (grid.contains(randNum) == false & randNum != 0 ) {
Should be this:
randNum = (int) (Math.random() * 9) + 1;
if (grid.contains(randNum) == false) {
since you multiply Math.random() * 9 you will only get numbers between 0-8, adding 1 will give you 1-9.
You are doing it wrong or unknowingly actually at several places:
& and && are two different things. Use && when you want to continue to check for second condition iff first operand or condition evaluates to true otherwise to evaluate both operands use &.
Why multiplying by 9. Multiply it by 10. As multiply by 9 constrained to 1-8 numbers only.
Why are you printing the grid within a loop and having a special loop for same?. Just print the grid it will show you all the elements.
Below is your corrected program:
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
ArrayList<Integer> grid = new ArrayList<Integer>();
int randNum;
int count = 0;
int size=8;
while (count <= size) {
randNum = (int) (Math.random() * 10);
System.out.println(randNum+"test"+grid);
if (!grid.contains(randNum) && randNum != 0 ) {
System.out.println("grid coming in here"+grid);
grid.add(randNum);
count++;
}
}
System.out.println(grid);
System.out.println("size: " + grid.size());
}
}
Hope it helps!

Java for loop to get X

I need help with a for loop I have for an assignment.
There is a math problem called N!, I bet some of you have heard of it. It goes like 1*2*3*4*5*n=x
I made a table like this:
1 = 1
1 * 2 = 2
1 * 2 * 3 = 6
1 * 2 * 3 * 4 = 24
1 * 2 * 3 * 4 * 5 = 120
1 * 2 * 3 * 4 * 5 * 6 = 720
But I just can't seem to solve the problem. How do I get what x is from 1*2*3*4....*n=x? Here's my code so far:
Scanner input = new Scanner(System.in);
System.out.println("\n~~Assignment 8.5~~");
boolean go = true;
do {
int n;
int total;
System.out.println("Loop until:");
n = input.nextInt();
for (int i = 1;i <= n;i++)
{
System.out.print(i);
if (i == n) { System.out.print(" = " + "idk" + "\n"); break;} else { System.out.print(" * ");}
}
} while ( go == true);
Just add total calculation s
inside the for loop:
total *= i;
and after the for loop print it. Remember to initialize total with value 1
You can use following Class;
public class RecursiveTest {
public RecursiveTest(int x){
int i=1;
int temptotal=1;
while(true){
System.out.print(i+"*");
if(temptotal==x || temptotal>x) break;
temptotal=temptotal*(++i);
}
}
public static void main(String[] args) {
new RecursiveTest(100);
}
}
Here's the hint,
fact(x) = x * fact(x-1) iff x > 0
fact(x) = 1 iff x == 0
fact(x) = ERROR iff x < 0
Create and implement the function public int fact(int x) and call it from inside a main function after picking up input from the command line or from reading user input. (and validating the input is a number)
int rec_n( int n){
int result = 1;
for(int i = 1; i <= n; i++ ){
result *= i;
}
return result;
}

Categories