How to draw an inverse pyramid with asterisks in Java - java

Code
public static void main(String[] args) {
String text=JOptionPane.showInputDialog("Introduce height");
int height=Integer.parseInt(text);
drawInversePiramid(height);
}
public static void drawInversePiramid(int height){
for(int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
//we draw spaces
for(int i=0;i<numberspaces;i++){
System.out.println(" ");
}//we draw the asterisks
for(int j=0;j<numberasterisks;j++){
System.out.println("*");
}//to jump the line
System.out.println("");
}
}
I'm having a trouble compiling the pyramid correctly. Instead it simply prints a vertical pattern with the correct number of asterisks.

Your code is actually correct, except for one minor detail. You are calling println everywhere, which will always print to a newline. Instead, only call println at the end of each line, but use just print when you want to build out a given line with stars and spaces. Using this version of your code:
public static void drawInversePiramid(int height) {
for (int numberasterisks=(height*2)-1,numberspaces=0;numberasterisks>0;numberspaces++,numberasterisks-=2){
// we draw spaces
for (int i=0; I < numberspaces; i++) {
System.out.print(" ");
}
// we draw the asterisks
for (int j=0; j < numberasterisks; j++) {
System.out.print("*");
}
// to jump the line
System.out.println("");
}
}
drawInversePiramid(3);
I get the correct output:
*****
***
*
Demo

Related

Print triangle with width and height parameters

I am quite new to programming and Java. I need to print an asteriks and dot triangle with respect to width and height parameters.
So far, I can print only asteriks triangle with an only one parameter (height). (Assume 6 is given as parameter to the function)
Here is my code:
public static void main(String[] args)
{
for(int i=0; i<6; i++)
{
for(int j=6; j>=i; j--)
{
System.out.print(".");
}
for(int x=0; x<=(2*i); x++)
{
System.out.print("*");
}
for(int k=6; k>=i; k--)
{
System.out.print(".");
}
System.out.print("\n");
}
}
I want to give two parameters(width and height) to the function. However, I cannot manage adding a second parameter.
The expected output is (with width -11- and height -8- parameters):
triangle 11 8
.....*.....
....**.....
...****....
...*****...
..******...
.********..
.*********.
***********
However, I got the following output (with one parameter which only height -6-):
triangle 6
.......*.......
......***......
.....*****.....
....*******....
...*********...
..***********..
Could you please help me? How can I add a second parameter to my function and fix my problem?
Thank you very much!
Your code is doing several things which do not match your example.
First, you aren't using the arguments at all. You said to assume 6 is passed to your main method as an argument, but all I see is hardcoded 6's in your code. You should be calling args[0] and args[1] to use the two arguments.
Second, your loop logic is off if you want to get the result given with the arguments provided in the example. Your outer loop is fine for the number of lines, but your inner loops don't build the individual lines exactly right. The tricky part here is that the contents of each line need to consider the ratio of the width to the height.
Here is an example which should fix both issues:
public static void main(String[] args) {
int width = Integer.parseInt(args[0]);
int height = Integer.parseInt(args[1]);
for(int i=0; i<height; i++) {
int starsThisLine = (int) Math.round(width * ((i+1) / (double) height));
int dotsBeforeStars = (int) Math.round((width - starsThisLine) / 2.0);
for(int j=0; j<width; j++)
{
if (j < dotsBeforeStars)
System.out.print(".");
} else if (j < dotsBeforeStars + starsThisLine) {
System.out.print("*");
} else {
System.out.print(".");
}
}
System.out.print("\n");
}
}
Note that this may not print the result exactly, but should look close enough. If you need it to be exact, you may need to tune the ratios a bit.

Printing a Triangle

I am having trouble printing a triangle. Using 2 loop statements in the printTriangle method, I have to make a triangle that looks like this.
If user entered 3
*
**
***
**
*
Using 2 loops in the triangle method that must use the printLine method to print this triangle. I cannot print anything at all in the triangle method and cannot change anything in the line method. Any help with a small explanation would be awesome, thanks!
import java.util.Scanner;
public class Triangle {
//Global declaration of the keyboard
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
int triSize = 0;
System.out.println("What size triangle would you like to be printed?");
triSize = kbd.nextInt();
printTriangle(triSize);
}
/**
* printLine is used to calculate how many asterisks should be printed
* #param astNum the number given by the user
* #param x is used to count the number of asterisks that have not and need to be printed
*/
public static void printLine(int astNum){
int x;
for (x = 0;astNum > x; x++){
System.out.print("*");
}
System.out.println("");
}
public static void printTriangle(int triSize){
int x = 0;
for (int i=1; i<=triSize; i++) {
printLine(triSize);
}
}
}
Using two loops in the printTriangle() method to generate the output is exactly how I would approach this problem. The first loop can print from 1 star to N stars, where N is the size of the triangle. Then, use a second loop to print the other half of the triangle. This is really an exercise in your ability to articulate clean loop boundary conditions in both loops.
public static void printTriangle(int triSize) {
// print stars from 1 to triSize, top to bottom
for (int i=1; i <= triSize; ++i) {
printLine(i);
}
// print starts from triSize-1 to 1, from top to bottom
// note carefully that the loop counter here begins at triSize - 1
for (int i=triSize-1; i >= 1; --i) {
printLine(i);
}
}
Add these loops:
for (int i=1; i<=triSize; i++) {
printLine(i);
}
for (int i=triSize; i>=1; i--) {
printLine(i);
}

Java Square Class [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is what I am asked to do:
1. Create a class called Square that takes a width parameter in the constructor. The Square class should have a draw() method that will draw the square on the screen. Create a class called TestSquare that will take width from the user, create an object of Square, and invoke the draw() method on the square object.
Here is what I have, but the problem I am having is passing the draw() method to the test method. I know see that I need to move the for loops from the test to the class, so that i can call it in the test main method.
public class Square {
/** the width of square*/
int width;
/** construct the square*/
Square(){
}
/**construct a square */
Square(int newWidth){
width = newWidth;
}
/**show the square*/
void draw(){
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("* ");}
System.out.println();
}
}
}
import java.util.Scanner;
public class TestSquare {
/** Main method */
public static void main(String[] args) {
// Create a scanner input
Scanner input = new Scanner(System.in);
// prompt user to enter width
System.out.println("Creating a Square ...");
System.out.print("Please enter its width:");
int width = input.nextInt();
Square square = new Square(width);
System.out.println("Here is the Square:");
square.draw();
}
}
Change your loop into this:
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
As said, remove semicolons after loops because this makes your loop end immediately without arguments. i should be set to 1 so that it would reiterate in the correct number of times
And edit your getWidth() method into this:
int getWidth() {
return width;
}
Using width*width would make the method return n^2 of the width. It's supposed to be width not area.
Edit: I'm not sure if this is what you're trying to do but try putting this inside Square class:
void draw() {
for (int i=0; i<width; i++)
{
for (int j=0; j<width; j++)
{ System.out.print("*"); }
System.out.println();
}
}
Remove the getWidth() method completely. Then replace your getWidth() invocation with this:
square.draw();
There are a few problems.
Either rename this method to "getArea" or return width only:
int getWidth() {
return width*width;
}
Do not put a semicolon at the end of the for loop declarations. That makes the for loop do nothing. Also, the outer for loop should start at 0 (not 1):
for (int i=1; i<width; i++); //remove this trailing semicolon
{
for (int j=0; j<width; j++); //remove this trailing semicolon
System.out.print("*");
System.out.println();
}

String Method and loops

I have a program I'm working on that I'm stuck on and can't really figure out. Basically, I'm supposed to input a word, and have the word be encased in a box of asterisks, which is the main objective. The actual prompt says: Read a string from the keyboard. Output the string centered inside of a box as shown below. The box needs to be resized on each run to assure that it has the correct spacing.
Ex.
Here is my code:
import java.io.*;
import java.util.*;
public class Prog600a
{
public static void main(String[] args)
{
for(int i = 1; i<=3; i++)
{
Scanner kbReader = new Scanner(System.in); //Allows input
System.out.print("Enter a string: ");
String word1 = kbReader.nextLine();
int len1 = word1.length();
for(int x = 0; x<=len1; x++)
{
System.out.print("*");
}
System.out.println();
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
System.out.println("* " + word1 + " *");
System.out.print("*");
for(int x = 0; x<len1; x++)
{
System.out.print("\t");
}
System.out.print("*");
System.out.println();
for(int x = 0; x<len1; x++)
{
System.out.print("*");
}
System.out.println();
}
}
}
I'm using the string method length to determine how long the string is, and print asterisks according to that. However, I can't seem to get the spacing, and my output looks nothing like the one shown. I've been experimenting with the code for a few hours (which is why it's a bit long and may be inefficient ), but can't really seem to get it. The spacing isn't right, and I don't really know how to correctly resize the box on each run. Can someone please provide some guidance? Thanks for all the help!
I spot only tiny problems:
You don't print enough asterisks in the top and the bottom (make it < len1 + 4)
You print tabs instead of spaces (change "\t" to " ").
You don't print enough spaces, change those loops to < len + 2
That's all. My output for input test:
********
* *
* test *
* *
********
Stack Overlow isn't for doing your homework for you. But, I will give you some pointers:
Look at repeat.
A tab character is 4-8 characters long, depending on how you're viewing it. '*' is one character long.

Making text stay in a group

I have a fairly simple question regarding Java. I am currently learning Java and one of the homework questions has me stumped. The goal is to create a triangle with the little figure. I believe I have the idea down however, I cannot get the whole figure of the guy to move to the right.
The code I have so far is:
public class LittleGuy {
public static final int NUMBER_OF_GUYS = 5; // determines the number of guys.
public static void main(String[] args) {
for (int line = 1; line <= NUMBER_OF_GUYS; line++){
for (int j = 1; j <= (-5 * line + 25); j++){// uses the algorithm.
System.out.print(" ");
}
guy();
}
}
public static void guy(){
System.out.print(" o ******\n /|\\ *\n / \\ *");
System.out.println();
}
}
Basically, the body and the head aren't supposed to be separated. I'm having trouble keeping them together. I am assuming that it is a fairly simple fix I am either unaware of or completely over looking. Any information or thought would be greatly appreciated. Thanks again.
You are only printing out the spaces before the first line of your little guy, inside the guy() method, you are still printing the rest of the guy on the first line.
I'd suggest making a printSpaces(int numSpaces) method which prints numSpaces spaces, and changing the guy method to take the number of spaces to print at the beginning of each line.
public class LittleGuy {
public static final int NUMBER_OF_GUYS = 5; // determines the number of guys.
public static void main(String[] args) {
for (int line = 1; line <= NUMBER_OF_GUYS; line++){
int counter=0;
for (int j = 1; j <= (-5 * line + 25); j++){// uses the algorithm.
System.out.print(" ");
counter++;
}
guy(counter);
}
}
public static void guy(int count){
System.out.print(" o ******");
System.out.print("\n");
for(int i=0;i<count;i++)
System.out.print(" ");
System.out.print("/|\\ *");
System.out.print("\n");
for(int i=0;i<count;i++)
System.out.print(" ");
System.out.print("/ \\ *");
System.out.println();
}
}
The problem was : In the guy() method you use \n to print the guy. But it will not take care of the white-spaces you printed in-order to achieve your algorithm (inside the for loop).
How it was solved : place a counter in the for loop to count how many white-spaces were printed and use that counter in the guy() method to print required white-spaces.

Categories

Resources