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);
}
Related
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.
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
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();
}
}
I can't even do the basics. What am I doing wrong?
I need to:
Draw a "X" made up of stars (*). I must prompt for the width of the X in stars.
My requirements for this assignment is:
+1 - prompt for size of X
+4 - draw X of stars (receive +2 if can draw solid square of stars)
I'm using Eclipse by the way!
import java.util.Scanner;
/*
*
*
* Description: Draws a X.
*/
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: 4 ");
int size = sc.nextInt();
for (i=0; i < size; i++)
{
for (j=0; j < size; j++)
{
if ( (i == 0) // First row
|| (i == size-1) // Last row
|| (j == 0) // First column
|| (j == size-1) ) // Last column
System.out.print("*"); // Draw star
else
System.out.print(" "); // Draw space
}
System.out.println();
}
}
} //
Your program draws a box correctly.
Enter size of box: 4 7
*******
* *
* *
* *
* *
* *
*******
You need to change your code so it draws a cross instead. The code is actually simpler as you have just two lines instead of four.
I would remove the 4 from the prompt as it confusing.
Enter size of box: 7
* *
* *
* *
*
* *
* *
* *
You already know you problem. You stated it yourself: "I can't even do the basics".
Then learn the basics. There is no way around THAT.
This site is not a "write me a piece of code that does X" service. People will help you only with specific questions on a specific problem. Your task is actually beginner stuff that is pretty simple once you grasped the basic concepts. Failing that, any solution we may provide here will be useless to you, since you don't even understand how the problem was solved. Worse, your teach will most likely notice pretty fast that you did not write that on your own. That screws you double - you get charged of cheating and still haven't learned anything.
Here is the skeleton of what you need. The for loops will iterate through the table. The hard part is coming up with the algorithm for deciding which character to print.
public class Tutorial1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int i,j;
System.out.print("Enter size of box: ");
size = sc.nextInt();
Tutorial1 t = new Tutorial1();
t.printX(size);
}
private int _size = 0;
public void printX(int size) {
_size = size;
for(int row = 0; row < _size;row++) {
for(int col = 0; col< _size;col++) {
System.out.print(getChar(row,col));
}
System.out.println();
}
}
private String getChar(int row, int col) {
//TODO: create char algorithm
//As a pointer, think about the lines of the X independently and
//how they increment/decrement with the rows
}
}
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.