Enter edge length of your rhomboid: 5
Here is your rhomboid:
*****
*****
*****
*****
*****
I need to print that rhomboid with scanner. I get like: * * * * * *
My code was like that normally I'm not that bad but i couldn't even do the first line:
import java.util.Scanner;
public class rhomboid {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter edge lenght of your rhomboid: ");
int edgelenght = scan.nextInt();
System.out.println("Here is your rhomboid:");
while(edgelenght > 0){
System.out.print(" ");
System.out.print("*");
edgelenght--;
So your code will just print 1D output..
Output:- *****
So, to solve this you need two loops one for row and column.Now a little modification in 2D printing for rhombus is, first now there must be gap of 4 spaces before printing,it can be achieved by using one more variable k as shown below.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter edge lenght of your rhomboid: ");
int edgelenght = scan.nextInt();
int k = edgelenght - 1;
for (int i = 0; i < edgelenght; i++) {
for (int j = 0; j < k + edgelenght; j++) {
if (j < k) {
System.out.print(" ");
} else {
System.out.print("*");
}
}
k--;
System.out.println();
}
}
What you get is what you wrote in your code.
while(edgelenght > 0){
System.out.print(" ");
System.out.print("*");
edgelenght--;
}
will print edgelenght times a space " " and after that a "*".
What you want is something like this:
for(int line = 0; line < edgeLength; line++){
// in line 0 print 4 spaces (5-1), in line 3 print 1 (5-1-3), in line 4 (the last one) print 0
for(int space = 0; space < edgeLength - line - 1; space++){
System.out.print(" ");
}
for(int asterix = 0; asterix < edgeLength; asterix++){
System.out.print("*");
}
// print a newline
System.out.println("");
}
You need to first loop over the lines.
For every line you need a loop to print spaces. And one to print *.
Related
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.
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!
I've learned a lot here, but there is a question I have that I can't sem to find.
Our last assignment, requires us to use nested For Loops in Java to display a diamond.
The Program must use a symbol entered by the user and draw the following:
%
% %
% % %
% % % %
% % % % %
% % % %
% % %
% %
%
So far, i pseudo coded one half triangle, and then I was going to code the inverse of the triangle to complete the opposite side, but I can not get any other than this without increasing the amount of symbols required:
*
**
***
****
*****
This is the code:
String symbol1; //User input, symbol to utilize
Scanner Keyboard = new Scanner (System.in);
System.out.println("Enter the Symbol you wish to use: ");
symbol1 = Keyboard.next();
for (int i=0 ; i<5 ; i++)
{
for (int k=5 ; k > i; k--)
{
System.out.print(" ");
}
for (int j=0; j<=i; j++)
{
System.out.print(symbol1);
}
System.out.println();
}
}
}
Any input is greatly appreciated!
*EDIT*
I wanted to post my end code.
It may be simple, but I feel accomplished.
Hopefully it will help someone at some point like I was helped here!
Cheers everyone.
import java.util.Scanner;
public class AlvaradoPgm04Bonus {
public static void main(String[] args) {
//Draw a diamond using symbol entered by user
String symbol1; //User input, symbol to utilize
Scanner Keyboard = new Scanner (System.in); //New scanner
System.out.println("Enter the Symbol you wish to use: "); //Prompt user symbol input
symbol1 = Keyboard.next(); // Capture user input
for (int i=0 ; i<5 ; i++){ //Begin for loop - increase until int is 5 long
for (int k=8 ; k > i ; k--){ //nested loop - decrease space before int "i" (inverted invisible triangle)
System.out.print(" "); //print space from nested loop before symbol1
}
for (int j=0; j<=i; j++){ //nested loop - increase "j" until is equal to "i"
System.out.print(symbol1 + " "); //print symbol1 + space to form diamond
}
System.out.println(); //print above nested loop line by line
} //begin new loop - inverted triangle
for (int m = 4 ; m > 0 ; m--){ //decrease symbol by 1
for (int n = 8 ; n >= m ; n--){ //match increase of space "invisible" triangle next to symbol to form upside down triangle
System.out.print(" "); //print "invisible" triangle
}
for (int q = 0 ; q < m ; q++){ //nested loop to decrease symbol entered by user
System.out.print(symbol1 + " "); //print inverted triangle made of user's input
}
System.out.println(); //print the loop in new line.
} //end loop
}//end main
} //end class
You might want to notice that in the expected output there are spaces after each symbol, since you know how to print a space and I would assume you know where you're printing your symbol it should be easy for you to add the printing of a space after a symbol.
Then you've got the half of the diamond, the bottom half is exactly the same In the opposIte dIrectIon If you get my hInt.
package moreloops;
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int input=in.nextInt();
int spac=input-1;
int min=1;
int max=input;
for(int i=0;i<input;i++){
for(int k=spac ; k>i;k--){
System.out.print(" ");
}
for(int j=0;j<min;j++){
System.out.print("*");
}
min+=2;
System.out.println();
}
for(int m=input-1;m>0;m--){
for(int n=spac;n>=m;n--){
System.out.print(" ");
}
for(int q=0;q<m;q++){
System.out.print("*");
}
System.out.println();
}
}
}
my output lol
5
*
**
*
package moreloops;
import java.util.Scanner;
public class Diamond {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
int input=in.nextInt();
int spac=input-1;
int min=1;
int max=input;
for(int i=0;i<input;i++){
for(int k=spac ; k>i;k--){
System.out.print(" ");
}
for(int j=0;j<min;j++){
System.out.print("*");
}
min+=2;
System.out.println();
}
for(int m=input-1;m>0;m--){
for(int n=spac;n>=m;n--){
System.out.print(" ");
}
for(int q=0;q<m;q++){
System.out.print("*");
}
for(int s=0;s<m-1;s++){
System.out.print("*");
}
System.out.println();
}
}
}
That will help
This is a homework question so I would like help, not an answer.
I'm trying to create 2 triangles out of numbers based on a number entered by the user.
"Enter a number between 2-9: "3"
1
12
123
1
21
321
IE2:
"Enter a number between 2-9: "5"
1
12
123
1234
12345
1
21
321
4321
54321
I have been able to get the first triangle complete. But when I add my nested loop it messes up my first triangle with the numbers developed from the nested loop. It also puts all the numbers in a straight vertical line. I've tried variations for different nest loops and even tried messing with a StringBuilder, but was still unsuccessful.
Here's what I have in code so far:
import java.util.Scanner;
public class NestedLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a Number between 2-9: ");
int width = input.nextInt();
String r = "";
for (int i = 1; i <= width; i++)
{
r = r + i;
System.out.println(r);
}
}
}
Again, I'm looking for help/understanding and not just an answer.
There are two aspects the 2nd part of the question.
You need to generate strings with the numbers in the reverse order:
You could do this by adding the numbers at the other end.
You could do this by reversing the strings.
You need to arrange that there are spaces to the left.
You could do this by adding the required number of spaces to the left end of the string.
You could do this by using the System.out.format(...) with a template that right aligns the string in a field with the required number of characters. (OK, that's a bit too obscure ...)
Or, you can build the string in a character array or string builder rather than using string concatenation.
The "trick" is to figure out what strategy you are going to use ... before you start cutting code.
try
int width = 5;
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// print numbers from 1 to current line number
for (int n = 1; n <= line; n++) {
System.out.print(n);
}
// end of line
System.out.println();
}
// add empty line between triangles
System.out.println();
// for all lines; number of lines = width
for (int line = 1; line <= width; line++) {
// printing padding spaces, number of spaces = with - line number
int nSpaces = width - line;
for (int i = 0; i < nSpaces; i++) {
System.out.print(" ");
}
// print numbers from number of current line to 1
for (int n = line; n >= 1; n--) {
System.out.print(n);
}
// end of line
System.out.println();
}
Can you just add another loop after your first loop like
String r = "";
String space = "";
for (int i = width; i >= 1; i--)
{
r = r + i;
System.out.println(r);
}
Try it. not yet tested
You need to use a queue.
eg. http://docs.oracle.com/javase/1.5.0/docs/api/java/util/LinkedList.html
Enque the numbers till you reach the max, and then start dequing them.
And while you dequeue, you need to apply the reverse
Queue<String> q = new LinkedList<String>();
for (int i = 1; i <= width; i++)
{
r = r + i;
q.add(r);
System.out.println(r);
}
while(!q.isEmpty()){
String j = q.remove();
//reverse j
System.out.println(reverse(j));
}
I leave the reversing part for you to do :)
public static void main(String[] args)
{
int n = 5;
for(int i=1; i<=n; i++)
{
for (int j=(n*2), k=n; j>1; j--)
{
if (k <= i)
{
System.out.print(k);
}
else
{
System.out.print('*');
}
k += (j)-1 > n ? -1 : 1;
}
System.out.println();
}
}
Just tried to implement in scala. Ignore if you don't like it..:-)
class Triangle extends App
{
val width = Console.readInt()
if (width < 2 || width > 9)
{
throw new RuntimeException()
}
var i, j = 1;
for (i <- 1 to width)
{
for (j <- 1 to i)
{
print(j)
}
print("\n")
}
for (i <- 1 to width)
{
for (dummy <- 1 to width-i)
{
print(" ")
}
for (j <- i to 1 by -1)
{
print(j)
}
print("\n")
}
}
My assignment in my Java course is to make 3 triangles. One left aligned, one right aligned, and one centered. I have to make a menu for what type of triangle and then input how many rows is wanted. The triangles have to look like this
*
**
***
****
*
**
***
****
*
***
*****
So far I was able to do the left aligned triangle but I can't seem to get the other two. I tried googling but nothing turned up. Can anyone help? I have this so far.
import java.util.*;
public class Prog673A
{
public static void leftTriangle()
{
Scanner input = new Scanner (System.in);
System.out.print("How many rows: ");
int rows = input.nextInt();
for (int x = 1; x <= rows; x++)
{
for (int i = 1; i <= x; i++)
{
System.out.print("*");
}
System.out.println("");
}
}
public static void rightTriangle()
{
Scanner input = new Scanner (System.in);
System.out.print("How many rows: ");
int rows = input.nextInt();
for (int x = 1; x <= rows; x++)
{
for (int i = 1; i >= x; i--)
{
System.out.print(" ");
}
System.out.println("*");
}
}
public static void centerTriangle()
{
}
public static void main (String args [])
{
Scanner input = new Scanner (System.in);
System.out.println("Types of Triangles");
System.out.println("\t1. Left");
System.out.println("\t2. Right");
System.out.println("\t3. Center");
System.out.print("Enter a number: ");
int menu = input.nextInt();
if (menu == 1)
leftTriangle();
if (menu == 2)
rightTriangle();
if (menu == 3)
centerTriangle();
}
}
Sample Output:
Types of Triangles
1. Left
2. Right
3. Center
Enter a number (1-3): 3
How many rows?: 6
*
***
*****
*******
*********
***********
Hint: For each row, you need to first print some spaces and then print some stars.
The number of spaces should decrease by one per row, while the number of stars should increase.
For the centered output, increase the number of stars by two for each row.
Ilmari Karonen has good advice, and I'd just like to generalize it a bit. In general, before you ask "how can I get a computer to do this?" ask "how would I do this?"
So, if someone gave you an empty Word document and asked you to create the triangles, how would you go about doing it? Whatever solution you come up with, it's usually not hard to translate it to Java (or any other programming language). It might not be the best solution, but (hopefully!) it'll work, and it may point you to a better solution.
So for instance, maybe you would say that you'd type out the base, then go up a line, then type the next highest line, etc. That suggests that you can do the same in Java -- create a list of Strings, base-to-top, and then reverse them. That might suggest that you can just create them in reverse order, and then not have to reverse them. And then that might suggest that you don't need the list anymore, since you'll just be creating and printing them out in the same order -- at which point you've come up with essentially Ilmari Karonen's advice.
Or, maybe you'd come up with another way of doing it -- maybe you'd come up with Ilmari Karonen's idea more directly. Regardless, it should help you solve this and many other problems.
Left alinged triangle-
*
**
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)each row contains star and no of stars i each row is incremented by 1.
So for Left alinged triangle we need to use 2 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing stars in each rows.
Code for Left alinged triangle-
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
Right alinged triangle-
*
**
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)In each row we need to print spaces followed by a star & no of spaces in each row is decremented by 1.
So for Right alinged triangle we need to use 3 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing spaces.
3rd "for loop" for printing stars.
Code for Right alinged triangle -
public void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop fr space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
Center Triangle-
*
* *
from above pattern we come to know that-
1)we need to print pattern containing n rows (for above pattern n is 4).
2)Intially in each row we need to print spaces followed by a star & then again a space . NO of spaces in each row at start is decremented by 1.
So for Right alinged triangle we need to use 3 for loop.
1st "for loop" for printing n row.
2nd "for loop for printing spaces.
3rd "for loop" for printing stars.
Code for center Triangle-
public void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
CODE FOR PRINTING ALL 3 PATTERNS -
public class space4
{
public static void leftTriangle()
{
/// here no of rows is 4
for (int a=1;a<=4;a++)// for loop for row
{
for (int b=1;b<=a;b++)for loop for column
{
System.out.print("*");
}
System.out.println();}
}
public static void rightTriangle()
{
// here 1st print space and then print star
for (int a=1;a<=4;a++)// for loop for row
{
for (int c =3;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int d=1;d<=a;d++)// for loop for column
{
System.out.print("*");
}
System.out.println();
}
}
public static void centerTriangle()
{
for (int a=1;a<=4;a++)// for lop for row
{
for (int c =4;c>=a;c--)// for loop for space
{
System.out.print(" ");
}
for (int b=1;b<=a;b++)// for loop for column
{
System.out.print("*"+" ");
}
System.out.println();}
}
public static void main (String args [])
{
space4 s=new space4();
s.leftTriangle();
s.rightTriangle();
s.centerTriangle();
}
}
package apple;
public class Triangle {
private static final int row = 3;
public static void main(String... strings) {
printLeftTriangle();
System.out.println();
printRightTriangle();
System.out.println();
printTriangle();
}
// Pattern will be
// *
// **
// ***
public static void printLeftTriangle() {
for (int y = 1; y <= row; y++) {
for (int x = 1; x <= y; x++)
System.out.print("*");
System.out.println();
}
}
// Pattern will be
// *
// **
// ***
public static void printRightTriangle() {
for (int y = 1; y <= row; y++) {
for (int space = row; space > y; space--)
System.out.print(" ");
for (int x = 1; x <= y; x++)
System.out.print("*");
System.out.println();
}
}
// Pattern will be
// *
// ***
// *****
public static void printTriangle() {
for (int y = 1, star = 1; y <= row; y++, star += 2) {
for (int space = row; space > y; space--)
System.out.print(" ");
for (int x = 1; x <= star; x++)
System.out.print("*");
System.out.println();
}
}
}
This is for normal triangle:
for (int i = 0; i < 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print(" *");
}
System.out.print("\n");
}
Output:
*
* *
* * *
* * * *
* * * * *
This is for left triangle, just removed space before printing *:
for (int i = 0; i < 5; i++) {
for (int j = 5; j > i; j--) {
System.out.print(" ");
}
for (int k = 1; k <= i + 1; k++) {
System.out.print("*");
}
System.out.print("\n");
}
Output:
*
**
***
****
*****
1) Normal triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=n-i;j++)
{
System.out.print(" ");
}
for(int k=0;k<=2*i;k++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
2) right angle triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=n-i;j++)
{
System.out.print(" ");
}
for(int k=0;k<=i;k++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
}
}
3) Left angle triangle
package test1;
class Test1 {
public static void main(String args[])
{
int n=5;
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
System.out.print("*");
}
System.out.println("\n");
}
}
}
I know this is pretty late but I want to share my solution.
public static void main(String[] args) {
String whatToPrint = "aword";
int strLen = whatToPrint.length(); //var used for auto adjusting the padding
int floors = 8;
for (int f = 1, h = strLen * floors; f < floors * 2; f += 2, h -= strLen) {
for (int k = 1; k < h; k++) {
System.out.print(" ");//padding
}
for (int g = 0; g < f; g++) {
System.out.print(whatToPrint);
}
System.out.println();
}
}
The spaces on the left of the triangle will automatically adjust itself depending on what character or what word you want to print.
if whatToPrint = "x" and floors = 3 it will print
x
xxx
xxxxx
If there's no automatic adjustment of the spaces, it will look like this (whatToPrint = "xxx" same floor count)
xxx
xxxxxxxxx
xxxxxxxxxxxxxxx
So I made add a simple code so that it will not happen.
For left half triangle, just change strLen * floors to strLen * (floors * 2) and the f +=2 to f++.
For right half triangle, just remove this loop for (int k = 1; k < h; k++) or change h to 0, if you choose to remove it, don't delete the System.out.print(" ");.
For the right triangle, for each row :
First: You need to print spaces from 0 to rowNumber - 1 - i.
Second: You need to print \* from rowNumber - 1 - i to rowNumber.
Note: i is the row index from 0 to rowNumber and rowNumber is number of rows.
For the centre triangle: it looks like "right triangle" plus adding \* according to the row index (for ex : in first row you will add nothing because the index is 0 , in the second row you will add one ' * ', and so on).
well for the triangle , you need to have three loops in place of two ,
one outer loop to iterate the no of line
two parallel loops inside the main loop
first loop prints decreasing no of loops
second loop prints increasing no of ''
well i could give the exact logic as well , but its better if you try first
just concentrate how many spaces and how many '' u need in every line
relate the no of symbols with loop iterating no of lines
and you're done
..... if it bothers more , let me know , i'll explain with logic and code as well
This will print stars in triangle:
`
public class printstar{
public static void main (String args[]){
int m = 0;
for(int i=1;i<=4;i++){
for(int j=1;j<=4-i;j++){
System.out.print("");}
for (int n=0;n<=i+m;n++){
if (n%2==0){
System.out.print("*");}
else {System.out.print(" ");}
}
m = m+1;
System.out.println("");
}
}
}'
Reading and understanding this should help you with designing the logic next time..
import java.util.Scanner;
public class A {
public void triagle_center(int max){//max means maximum star having
int n=max/2;
for(int m=0;m<((2*n)-1);m++){//for upper star
System.out.print(" ");
}
System.out.println("*");
for(int j=1;j<=n;j++){
for(int i=1;i<=n-j; i++){
System.out.print(" ");
}
for(int k=1;k<=2*j;k++){
System.out.print("* ");
}
System.out.println();
}
}
public void triagle_right(int max){
for(int j=1;j<=max;j++){
for(int i=1;i<=j; i++){
System.out.print("* ");
}
System.out.println();
}
}
public void triagle_left(int max){
for(int j=1;j<=max;j++){
for(int i=1;i<=max-j; i++){
System.out.print(" ");
}
for(int k=1;k<=j; k++){
System.out.print("* ");
}
System.out.println();
}
}
public static void main(String args[]){
A a=new A();
Scanner input = new Scanner (System.in);
System.out.println("Types of Triangles");
System.out.println("\t1. Left");
System.out.println("\t2. Right");
System.out.println("\t3. Center");
System.out.print("Enter a number: ");
int menu = input.nextInt();
Scanner input1 = new Scanner (System.in);
System.out.print("maximum Stars in last row: ");
int row = input1.nextInt();
if (menu == 1)
a.triagle_left(row);
if (menu == 2)
a.triagle_right(row);
if (menu == 3)
a.triagle_center(row);
}
}
public static void main(String[] args) {
System.out.print("Enter the number: ");
Scanner userInput = new Scanner(System.in);
int myNum = userInput.nextInt();
userInput.close();
System.out.println("Centered Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
System.out.print(" ");
}
for (int j = 0; j < i; j++) { //Prints a " " followed by '*'.
System.out.print(" *");
}
System.out.println(""); //Next Line
}
System.out.println("Left Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int j = 0; j < i; j++) { //Prints the '*' first in each line then spaces.
System.out.print("* ");
}
System.out.println(""); //Next Line
}
System.out.println("Right Triange");
for (int i = 1; i <= myNum; i+=1) {//This tells how many lines to print (height)
for (int k = 0; k < (myNum-i); k+=1) {//Prints spaces before the '*'
System.out.print(" ");
}
for (int j = 0; j < i; j+=1) { //Prints the " " first in each line then a "*".
System.out.print(" *");
}
System.out.println(""); //Next Line
}
}
This is the least complex program, which takes only 1 for loop to print the triangle. This works only for the center triangle, but small tweaking would make it work for other's as well -
import java.io.DataInputStream;
public class Triangle {
public static void main(String a[]) throws Exception{
DataInputStream in = new DataInputStream(System.in);
int n = Integer.parseInt(in.readLine());
String b = new String(new char[n]).replaceAll("\0", " ");
String s = "*";
for(int i=1; i<=n; i++){
System.out.print(b);
System.out.println(s);
s += "**";
b = b.substring(0, n-i);
System.out.println();
}
}
}
For left aligned right angle triangle you could try out this simple code in java:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int size=sc.nextInt();
for(int i=0;i<size;i++){
for(int k=1;k<size-i;k++){
System.out.print(" ");
}
for(int j=size;j>=size-i;j--){
System.out.print("#");
}
System.out.println();
}
}
}
Find the following , it will help you to print the complete triangle.
package com.raju.arrays;
public class CompleteTriange {
public static void main(String[] args) {
int nuberOfRows = 10;
for(int row = 0; row<nuberOfRows;row++){
for(int leftspace =0;leftspace<(nuberOfRows-row);leftspace++){
System.out.print(" ");
}
for(int star = 0;star<2*row+1;star++){
System.out.print("*");
}
for(int rightSpace =0;rightSpace<(nuberOfRows-row);rightSpace++){
System.out.print(" ");
}
System.out.println("");
}
}
}
*
***
*****
*******
*********
***********
*************
For center triangle
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int b=(n-1)*2;
for(int i=1;i<=n;i++){
int t= i;
for(int k=1;k<=b;k++){
System.out.print(" ");
}
if(i!=1){
t=i*2-1;
}
for(int j=1;j<=t;j++){
System.out.print("*");
if(j!=t){
System.out.print(" ");
}
}
System.out.println();
b=b-2;
}
output:
*
* * *
for(int i=1;i<=5;i++)
{
for(int j=5;j>=i;j--)
{
System.out.print(" ");
}
for(int j=1;j<=i;j++)
{
System.out.print("*");
}
for(int j=1;j<=i-1;j++)
{
System.out.print("*");
}
System.out.println("");
}
*
***
public class Triangle {
public static void main ( String arg[] ) {
System.out.print("Enter Triangle Size : ");
int num = 0;
try {
num = Integer.parseInt( read.readLine() );
} catch(Exception Number) {
System.out.println("Invalid Number!");
}
for(int i=1; i<=num; i++) {
for(int j=1; j<num-(i-1); j++) {
System.out.print(" ");
}
for(int k=1; k<=i; k++) {
System.out.print("*");
for(int k1=1; k1<k; k1+=k) {
System.out.print("*");
}
}
System.out.println();
}
}
}
Target output:
*
***
*****
Implementation:
for (int i = 5; i >= 3; i--)
for (int a = 1; a <= i; a++)
{
System.out.print(" ");
}
for (int j = 10; j/2>=i; j--)
{
System.out.print("*");
}
System.out.println("");
}
(a) (b) (c) (d)
* ********** ********** *
** ********* ********* **
*** ******** ******** ***
**** ******* ******* ****
***** ****** ****** *****
****** ***** ***** ******
******* **** **** *******
******** *** *** ********
********* ** ** *********
********** * * **********
int line;
int star;
System.out.println("Triangle a");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= line; star++ )
{
System.out.print( "*" );
}
System.out.println();
}
System.out.println("Triangle b");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line<star)
System.out.print( "*" );
else
System.out.print(" ");
}
System.out.println();
}
System.out.println("Triangle c");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line<=star)
System.out.print( "*" );
//else
// System.out.print(" ");
}
System.out.println();
}
System.out.println("Triangle d");
for( line = 1; line <= 10; line++ )
{
for( star = 1; star <= 10; star++ )
{
if(line>10-star)
System.out.print( "*" );
else
System.out.print(" ");
}
System.out.println();
}
You might be interested in this too
Scanner sc = new Scanner(System.in);
int n=sc.nextInt();
int b=0;
for(int i=n;i>=1;i--){
if(i!=n){
for(int k=1;k<=b;k++){
System.out.print(" ");
}
}
for(int j=i;j>=1;j--){
System.out.print("*");
if(i!=1){
System.out.print(" ");
}
}
System.out.println();
b=b+2;
}
Output:: 5
* * * * *
* * * *
* * *
* *
*