Printing an arrowhead of stars using nested for loops - java

Print an arrowhead.
Let the user input how big the arrow should be by entering the total number of lines to draw.
The user entered 9 in the example below. Prompt the user to enter an odd number only.
It should model this:
*
**
***
****
*****
****
***
**
*
So far my code looks like this:
int i, j, numRows;
Scanner reader=new Scanner(System.in);
System.out.println("How many rows would you like the triangle to have?");
numRows=reader.nextInt();
//row
for(i=1;i<=numRows;i++){
//column
for(j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
this is the top half. i can make the bottom half by altering the nested loop. I know that I need to have the nested loop decrease the amount of stars after it reaches the middle column, or (i/2)+1, but I am not sure how to do this. I tried using an if statement with j-- inside of the column loop but either that is not correct or I made a mistake.

put this for bottom half:
for(i=numRows;i>=0;i--){
for(j=i-1;j>0;j--){
System.out.print("*");
}
System.out.println();
}

You can use two nested loops similar to what you have now. Think about what starting value the inner loop should use and what the condition of the loop should be.

int i, j, numRows;
int modifier=1;
Scanner reader=new Scanner(System.in);
System.out.println("How many rows would you like the triangle to have?");
numRows=reader.nextInt();
//row
for(i=1;i>0;){
//column
for(j=1;j<=i;j++){
System.out.print("*");
}
System.out.println();
if (i == numRows) {
modifier=-1;
}
i=i+modifier;
}
I really shouldn't be doing your homework... but i always get sucked into these questions cuz they're trivial and sorta fun for me to solve...
My professors would always think I was strange because I never answered the problem the most straight-forward manner. :)

public static void printStarArrow() {
int i = 0;
int j = 0;
int numRows = 0;
Scanner reader = new Scanner(System.in);
System.out
.println("How many rows would you like the triangle to have?");
numRows = reader.nextInt();
if (numRows <= 0 || numRows % 2 != 1) {
System.out.println("Please enter an odd number only.");
return;
}
// row
for (i = 1; i <= numRows; i++) {
if (i <= (numRows / 2) + 1)
j = i;
else
j = --j;
printStar(j);
}
}
public static void printStar(int size) {
for (int i = 0; i < size; i++) {
System.out.print("*");
}
System.out.println("");
}

Related

Nested loop to print a number, with the same amount of astericks along side it

I'm trying to write a program that prompts the user for a number (between 5 and 50 (inclusive)), then output to screen a countdown of the numbers starting with the given number and include on the same line the same number of asterisks.
E.g. 5 ***** 4 **** 3 *** etc….
I know I need a scanner and a nested for loop, but I'm unsure to which way to use these together, any tips?
//outer loop
for (int outer = 50; outer <= 5; outer--) {
//inner loop
for (int inner = 1; inner <= outer; inner++) {
I've no idea how to start using the scanner in this situation!
This may help:
Scanner scanner = new Scanner(System.in);
int count = scanner.nextInt();
for(int i = count; i > 0; i-- ){
System.out.print(i);
for(int j=i; j>0; j-- ){
System.out.print("*");
}
System.out.println();
}

Print rows of triangle if a user specifies (more than 0)

I want the code to do this:
If I enter '5' it would print 5 triangle rows like this:
+
++
+++
++++
+++++
I also want to inverse it afterwards so that it looks like so:
+++++
++++
+++
++
+
This is my attempt:
package test;
import java.util.Scanner;
public class Testo1
{
public static void main(String[] args)
{
//
Scanner input = new Scanner(System.in);
int Rows = 0;
//
while(Rows<=0){
System.out.print("How many rows do you want in your triangle, more than 0?: ");
Rows = input.nextInt();
}while(Rows>=0){
//Honestly, I don't know what to do here or the logic to implement.
}
}
}
I commented the part in the while loop where I got lost. I want this in a while-loop nest. Can someone please guide me?
Yes, you have to do it with nested-loops.
Take a look at this code:
Scanner input = new Scanner(System.in);
int Rows = 0;
while (Rows <= 0) { // Keep asking the user if they enter something less than zero
System.out.print("How many rows do you want in your triangle, more than 0?: ");
Rows = input.nextInt();
}
// If you got out of the while loop, that means you got a positive row number
for (int i = 1; i <= Rows; i++) { // number of lines
for (int j = 1; j <= i; j++) // number of stars at each line
System.out.print("*"); // printing stars
System.out.print("\n"); // line break
}
For the inverse, you just change the loops to:
for (int i = Rows; i >= 1; i--) {
for (int j = i; j >= 1; j--)
System.out.print("*");
System.out.print("\n");
}
You can achieve any pattern just with the help of looping and by focusing
that how they actually work and print. Giving an example of a normal triangle printing:-
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if((i+j)>n)
{
System.out.print("#");
}
else
{
System.out.print(" ");
}
}
System.out.println();
}
The output would be:-
#
##
###
####
#####
Same way, you can make changes and produce different output. For example, change # with empty string, and you'll get the reversing order.
#####
####
###
##
#
Another pattern you can make is:-
Scanner scn=new Scanner(System.in);
int n=scn.nextInt();
for(int i = 0; i < n; i++){
for(int j=i+1;j>0;j--){
System.out.print("*");
}
System.out.println();
}
This will output as:-
*
**
***
****
*****
I hope this helps.

Java - How to create alternating triangle pyramid?

I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input. The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
The code I have written to achieve this is:
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
for (int j = 0; j < rows-i; j++){
System.out.print(star);
}
for (int k = 0; k <= i; k++){
System.out.print(circle);
}
System.out.println();
}
However, the output from my code does not match the pyramid above. The output of my code, with a user input of "6", is:
******o
*****oo
****ooo
***oooo
**ooooo
*oooooo
After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is. I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.
You could approach it another, far simpler, way.
In pseudo code:
create a String of n spaces
add "*" to it
loop n times, each iteration of the loop:
print it
replace " *" with "*O*"
This recognises a simple way to create the first line, and a simple way to create the next line from the previous line. Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.
Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).
A couple of ways to create a String of n spaces:
A loop that adds ' ' each iteration
new String(new char[n]).replace('\0', ' ')
How to replace certain characters of a String with other characters:
str = str.replace(" *", "*O*");
This method will work fine:
public void printPyramid (int input) {
for (int row = 1; row <= input; row++) {
for (int whitespace = input - 1; whitespace >= row; whitespace--) {
System.out.print(" ");
}
System.out.print("*");
for (int circle = 1; circle < row; circle++) {
System.out.print("o*");
}
System.out.println();
}
}
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
*o*o*o*o*o*o*
*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*o*
Welcome to Stack Overflow!
First, the "o"s and "*"s are not alternating because the for loops execute until completion. This means the stars and circles will print out separately. For this application you only need one for loop and two if statements based on whether the "i" in the for loop is odd or even. An easy way to do this is with the modulo function :
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
if ((i % 2) == 0)
{
System.out.print(circle);
}
else
{
system.out.print(star);
}
System.out.println();
}
See if that works.
Thanks!
Here is a solution, easy to understand and friendly for beginners.
(If you want to go more advanced, look at the solution from #Bohemian♦ )
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
// How many "o" do we need?
int count_circle = i;
// How many * do we need?
int count_star = count_circle + 1;
// Let's create the string with o and *
String output = "";
for(int j = 0; j < (count_circle + count_star); j++){
if(j % 2 == 0) // if it is odd
output = output + star;
else // if it is even
output = output + circle;
}
// Do we need spaces at the beginning?
String spaces = "";
for(int j = 0; j < rows - i - 1; j++){
spaces = spaces + " ";
}
// Final output
output = spaces + output;
System.out.println(output);
}
Try this.
Scanner in = new Scanner(System.in);
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; ++i) {
System.out.printf("%" + (rows - i) + "s", "*");
for (int j = 0; j < i; ++j)
System.out.print("o*");
System.out.println();
}
Ex:
If rows=3
*##
**#
***
class Main{
public static void main(String x[]){
Scanner scan=new Scanner(System.in);
int rows=scan.nextInt();
for(int i=1;i<rows;i++){
for (int j=0;j<i;j++)
{
System.out.print("*");
}
for (int j=rows;j>i;j--)
{
System.out.print("#");
}
System.out.println();
}
}
}
See if that works.
Thanks!

How to use nested for loops?

This is my code
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
int tri, a;
int b;
System.out.println("Enter the size you want your triangle to be:");
tri = keyboard.nextInt();
for (a = 1; a <= tri; a++)
{
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
}
}
When i run and enter ex. 3 i want the code to say
I know i might be missing some loops as I am in the beginning stages of the code only. I am running to see if everything goes as i want and it isn't. When i enter 3 i get everything on one line:
******
Help with explanation would be appreciated.
It should work with any number not just 3
You need to make two changes to your code. First, you need to end the line on each iteration of the outer loop. Second, you need to do the bottom part of the triangle. Here's code that does it both:
public static void main (String[] args)
{
Scanner keyboard = new Scanner (System.in);
int tri, a;
int b;
System.out.println("Enter the size you want your triangle to be:");
tri = keyboard.nextInt();
for (a = 1; a <= tri; a++)
{
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
// this next call ends the current line
System.out.println();
}
// now for the bottom of the triangle:
for (a = tri - 1; a >= 1; a--) {
for (b = 1; b <= a; b++)
{
System.out.print("*");
}
System.out.println();
}
}
Or just one loop:
int x = 3; // input tri
var y = x*2;
for (int i = 0; i < y; ++i) {
for (int j = 0; j < (i < x ? i : y-i); ++j) {
System.out.print("*");
}
System.out.println();
}
System.out.print prints everything in the current output buffer i.e. the console. You must use System.out.println (note the ln suffix) to print something and a break line.
This needs to be done every time the outer loop is accessed:
system.out.println();
this allows the *'s to be on different lines, also this code only does the top half of the triangle. In order to do the bottom half, you have to count down from tri.

"While-loop" not working right

I am learning java, using the book "Java how to program". I am solving exercises. In this actual exercise I am supposed to make a program which reads an integer from the user. The program should then display a square of asterisks (*) corresponding to the integer read from the user. F.eks user inputs the integer 3, the program should then display:
***
***
***
I try to nest a while-statement inside another, the first one to repeat the asterisks on one line, the other one to repeat this the right amount of times. Unfortunately, I only get the program to display one line. Could anyone tell me what I am doing wrong please?
The code is as follows:
import java.util.Scanner;
public class Oppgave618
{
public static void main(String[] args)
{
int numberOfSquares;
Scanner input = new Scanner(System.in);
System.out.print("Type number of asterixes to make the square: ");
numberOfSquares = input.nextInt();
int count1 = 1;
int count2 = 1;
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count2++;
}
}
}
You should reset count1 back in each iteration of the outer loop
public static void main(String[] args) {
int numberOfSquares;
Scanner input = new Scanner(System.in);
System.out.print("Type number of asterixes to make the square: ");
numberOfSquares = input.nextInt();
//omitted declaration of count1 here
int count2 = 1;
while (count2 <= numberOfSquares) {
int count1 = 1; //declaring and resetting count1 here
while (count1 <= numberOfSquares) {
System.out.print("*");
count1++;
}
System.out.println();
count2++;
}
}
count1 needs to be reset every time you move to the next line, e.g.
while (count2 <= numberOfSquares)
{
while (count1 <= numberOfSquares)
{
System.out.print("*");
count1++;
}
System.out.println();
count1 = 1; //set count1 back to 1
count2++;
}
Unless the exercise requires while-loops, you really should use for-loops. They will actually prevent such bugs from occurring, and require less code. Also, it is idiomatic in most programming languages to start counting from zero and use < rather than <= to terminate the loop:
for (int count2 = 0; count2 < numberOfSquares; ++count2)
{
for (int count1 = 0; count1 < numberOfSquares; ++count1)
System.out.print("*");
System.out.println();
}

Categories