Print triangle with width and height parameters - java

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.

Related

For() loop with constant variable isn't printing any output

The problem is that there is no output happening, not an extra println(). This is odd, because doing this programming without a static SIZE var, it works just fine.
public class SlashFigure2
{
public static final int SIZE = 4;
public static void main(String[] args)
{
for(int i = 1; i <= SIZE; i++)
{
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("\\");
}
for(int j = 1; j <= -4 * i + (-4 * SIZE + 2); j++)
{
System.out.print("!");
}
for(int j = 1; j <= 2 * i - (2 * SIZE + 2); j++)
{
System.out.print("/");
}
System.out.println();
}
}
}
In case anyone needs it, here's what the program prints:
!!!!!!!!!!!!!!
\\!!!!!!!!!!//
\\\\!!!!!!////
\\\\\\!!//////
EDIT: Here's what the site keeps saying is the error
EDIT 2:
The site is practiceit.csu.washington.edu
Here is the question's wording:
Modify your DollarFigure program from the previous exercise to become
a new program called DollarFigure2 that uses a global constant for the
figure's height. (You may want to make loop tables first.) The
previous output used a constant height of 7. The outputs below use a
constant size of 3 (left) and 5 (right)
Here are the outputs below they are talking about
(You must solve this problem using only ONE public static final
constant, not multiple constants; and its value must be used in the
way described in this problem.)
Simply do this:
if (i != SIZE) {
System.out.println();
}
Because i will be equal to SIZE in the last iteration, and you want to skip the println() in that case.
UPDATE
From the comments and the image, it's clear that you're not supposed to define SIZE as a constant, apparently you should be able to pass n as a parameter to your program, it's not a hardcoded value. Check the rules of the "site" you keep referring to, how's the input supposed to be received?
You can make this change in your code to make it work.You should not execute the statement when i is equal to SIZE
if(i<SIZE){
System.out.println();
}
Somewhat Jeopardy to find out the actual problem/quest you want to solve by algorithmically print a specific ASCII-art only denoted by a constant ROW-size (e.g. 4 or 6 as depicted on the attached image).
Tests & sample output
Derived specification
Draw a specific figure varying only in its height:
only single parameter is passed: rows of ASCII-art to draw
figure to draw should resemble a downward-arrow
bordered by double-slashes left and right, i.e. \\ respective //
no border/slashes on the first row
inner/rest of the rows filled with exclamation-marks !!
at least 2 exclamation-marks !! on the inner last row
Java method with single parameter: ROWS
private static void drawAsciiArt(int rows) {
int columns = (rows-1)*4+2;
for(int i = 1; i <= rows; i++) {
int borderSize = (i-1)*2;
int fillSize = columns - borderSize*2;
for(int j = 1; j <= borderSize; j++) {
System.out.print("\\");
}
for(int j = 1; j <= fillSize; j++) {
System.out.print("!");
}
for(int j = 1; j <= borderSize; j++) {
System.out.print("/");
}
if (i < rows) {
System.out.println();
} // if not last row
} // end of row-loop
}
Try this online
Figured it out! It turns out that for both the '\' and '/' characters, I didn't need to use that (x * SIZE + y) formula after all. They both needed the regular formula while the '!' is the only character that needed the SIZE formula
public class SlashFigure2
{
    public static final int SIZE = 4;
//program works no matter what value SIZE holds
    public static void main(String[] args)
    {
        for(int i = 1; i <= SIZE; i++)
        {
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("\\");
            }
            
            //note the SIZE formula in here
            for(int j = 1; j <= -4 * i + (4 * SIZE + 2); j++)
            {
                System.out.print("!");
            }
            
            for(int j = 1; j <= 2 * i - 2; j++)
            {
                System.out.print("/");
            }
            
            System.out.println();
        }      
    }  
    
}

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

Very basic java program doesnt run [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
So I am a java newb, started last week and have been reading a book. In the book at the end of a chapter it gives a challenge to make a program that will output
*
**
***
I am trying to get it so that it outputs is the number of lines as args (That is correct right?). The issue i am having is it the program will only output a page of asterisks as in:
***************...
The code is
public class Rektifier {
public static void main(String[] args) {
int Lines = 1; // amount of lines i want
int stars = 0; //asterisk i want
int X = 0; //Counter for the asterisks for loop
while (Lines <= Integer.parseInt(args[0])){ //I think I found this on stack overflow, it is to search through the arguments for integers
Lines =+ 1; // increase by 1 for the while loop
stars =+ 1; // do this to increase by 1 for the amount of stars i want, could be any number
for (X = 0; X >= stars; X =+ 1){ // forloop, if x is less than stars it should add * to the end of the line. Then increase x by 1 to add another star until x is equal to star then it should continue
System.out.print("*");
}
System.out.println(); //creates a new line to add on too
}
}
}
You have two loops. The outer while() loop uses Lines as its control variable. This loop decides how many stars are to be printed in each line – therefore Lines should take the values: 1, then 2, then 3, etc... (as for now it does not due to a small typo: so you should replace Lines=+1 with Lines+=1)
Your inner for loop uses X as its control variable. This loop actually prints the number of stars dictated by the Lines variable, so you should correct it to the form:
for (X = 0; X < Lines; X++)
Your variable stars is not necessary in such case.
(btw. refrain from starting variable names with capital letters; this works perfectly but is against tradition).
Or you can simply use for loops. You have nested 2 iterations. For loop is better for this case. Use while when execution count depends on some mutable condition.
public static void main(String[] args) throws IOException {
int lines = 3;
// lines loop
for(int i=0; i<lines; i++){
// stars loop
for(int j=0; j<=i; j++) {
System.out.print("*");
}
System.out.println();
}
}
For this easy learning example you could do string operation to get the result you want
public static void main(String[] args) {
int lineCount = Integer.parseInt(args[0]));
String stars = "";
for (int index = 0; index < lineCount; ++index) {
stars += "*";
System.out.println(stars);
}
}
This will produce the following output for arg = 10:
*
**
***
****
*****
******
*******
********
*********
**********
Every iteration the stars string will append a star to the existing stars.
There's answers here but they aren't pointing out the actual bugs in your code. I'll point out the bugs in your code. First and foremost:
What you need to do is first think of what the pseudocode looks like. It should look like this.
for (line_number ... number of lines):
for(0...line_number)
print star
print newline.
Here's the bugs in your code with comments in the lines:
public class Rektifier {
public static void main(String[] args) {
int Lines = 1;
int stars = 0; //This is not useful. The number of stars will always be equal to the number of lines. Why not just use the number of lines?
int X = 0; //Would rather that you utilize the for loop for declaring X, it is only used there.
while (Lines <= Integer.parseInt(args[0])){
Lines =+ 1; // Increment at the end of the while loop. Otherwise, you print two stars on the first line.
stars =+ 1; // Again not used.
for (X = 0; X >= stars; X =+ 1){ // your for loop is wrong; it reads like this. for x = 0 and x is bigger than stars, do blah. then you don't actually increment X because it should be X += 1 not X =+ 1.
System.out.print("*");
}
System.out.println(); //creates a new line to add on too
}
}
}
Here's a working implementation of your code using the same structure you are using.
public static void main(String[] args) {
int lines = 1;
while (lines <= Integer.parseInt(args[0])){
for (int x = 0; x < lines; x += 1){
System.out.print("*");
}
lines += 1;
System.out.println();
}
}

Java loops - making a "V"

This might sound like a slightly odd question, so bear with me.
What I'm tasked to do, is to make a simple Java class that forms a "V" based on whatever height the user would desire, made out of stars "*", and spaces " ".
For example, if a user desires a "V" with a height of 3, it would look print out something like;
* *
* *
*
Where a "V" with a height of 5 would look something like:
* *
* *
* *
* *
*
(That one didn't look too good, but you get the point, it's suppose to be 5 "high" and shaped like a "V")
The problem I have, is that I don't see what loops within loops within loops I would need to build something like this.
All the easy stuff like asking the user what height they want and such, I can handle, but I don't see how this thing is suppose to be coded, to print out a decent-looking and right-sized "V" in the console.
Can anyone assist me in this odd matter?
UPDATE
So in order to not come off as lazy, I tried poking around a little to see what I could come up with. Thanks to that and some help from the comments section, I came up with something like this.
public static void main(String[] args) {
int height = 3;
for (int i = 0; i < height; i++) {
for (int j = 0; j < 2*(height-1)+1; j++) {
if(j == i) {
System.out.print("*");
} else {
System.out.print(" ");
}
}
}
Looked like something of a good start, and it drew me half of the "V" in the size I wanted.
Am I on to it here, or am I on the moon in terms of progress?
I would love a poke in the right direction, and I do appreciate your comments guys!
Here is a code that draws V.
Look at it, you will understand why it works....
void drowV(int hight){
int rowLen = (hight-1)*2;
for(int i=0; i<hight; i++){
int start = i;
int end = rowLen-i;
for(int j=0;j<=rowLen; j++){
if(j==end){
System.out.println("*");
break;
}
else if(j==start){
System.out.print("*");
}
else{
System.out.print(" ");
}
}
}
}

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