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.
Related
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
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);
}
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'm having trouble figuring out This last pattern in a java assignment. I know I'm close but I can't figure it out here's my code:
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
int x = 6; // Counter?
for (int j = 1; j<=i; j++){ //column
System.out.print("");
x--;
}
for(int k=1;k<=i;k++) {
System.out.print(x);
}
System.out.println();
}
}
I understand that the outer loop is the rows and the inner the columns, but that's not the part I have wrong. My pattern it self is right but not the out put of the numbers.
I can't put my output on here because it won't format right. But if you copied my code exactly instead of a line of 0,then 1, then, 2... etc, I'm trying to get 1 2 3 4 5 6 on the top line, then 1 2 3 4 5, the next line and so on...
You were actually very close to the correct pattern, you just added a little too much. As a general tip (not always but most of the time), when making these loop patterns you can usually print these patterns using the integers in your loops. I changed your code a little bit to give you the pattern you wanted. You didn't need x as a counter because you can just use your deepest nested loop's integer as a counter, which in how I just adjusted your code is j because it will run for 6 times on the first then 5 on the second and so on. Another extra part that you added was the 3rd nested loop. It essentially did the exact same thing that the 2nd loop does because they both had the condition of running while they were less than i. Well here is the code; I hope my explanation helped.
public static void main(String[]args){
System.out.println("Pattern D:");
for (int i = 6; i>=1; i--) { // row
for (int j = 1; j<=i; j++){ //column
System.out.print(j);
} System.out.println();
}
}
Here is your expect code:
import java.util.*;
public class Test{
public static void main(String[]args){
System.out.println("Pattern D:");
for(int i=6 ;i >= 1;i--){
int k=i;
for (int j=1 ;j<=k; j++){
System.out.print(j);
}
System.out.println();
}
}
}
Turns out I said what I was trying to do earlier wrong. I wanted to right justify the pattern but here is my solution. Sorry for any confusion.
for (i=6;i>0;i--) {
x=6;
for (j=i;j<6;j++) {
x--;
System.out.print(" ");
}
for(k=1;k<=i;k++) {
System.out.print(x--);
}
System.out.println(" ");
}
public class TestPattern {
public static void main(String[] args) {
for (int i = 6; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Output:
123456
12345
1234
123
12
1
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.