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();
}
}
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.
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);
}
Was doing some Java practices and I got stuck at this particular question, I am given the following code:
public class DistanceSeparator {
public static void main(String[] args) {
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
public static void printSeparatorSequence(int numberOfElements) {
for () {
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
And I am supposed to modify the code using A SINGLE FOR LOOP to show that:
If numberOfElements = 5
1 3 7 13 21
If numberOfElements = 7
1 3 7 13 21 31 43
Each showing an increment of + 2, +4, +6, +8, +10 and +12
The final output is to be this:
1 3 7
1 3 7 13 21
1 3 7 13 21 31 43 57
I just can't seem to get my head around how to get that outcome, and this is after 2hours of trying (yes I am that bad). Any help, please?
edit This was what I had, before deciding to seek help, it's obviously not working.
int j = 0;
for (int i = 1; i <= numberOfElements; i++) {
j = i * 2; // + by how much
int z = i + j; //sum
System.out.print(z + "");
}
edit 2 now I get it, oh my, to think I was so close. Guess I was too cluttered after being stuck for some time. Thanks a ton!
Here is the code to accomplish result you expected.
int current = 1;
for(int i = 0; i < numberOfElements; i++) {
current += i*2;
System.out.print(current + " ");
}
You just need to keep another variable to keep track of the difference (the change), and then constantly update it by the power of 2 of the iteration, i.e. for the first loop only increase it by 2^1, then by 2^2, then 2^3 and so on).
An example of how to achieve that:
for (int i = 0, diff = 0; i < numberOfElements; i++, diff += 2*i) {
System.out.print((1 + diff) + " ");
}
UPDATE: After you've edited your question with your code segment, you can see your problem was with this line:
int z = i + j; //sum
Since both i and j advance with each iteration, you lose your offset (you constantly reset it). You need to keep it static (like in my example: 1), and only update j by 2*i each iteration, otherwise your "base" for calculation is constantly changing and the formula doesn't hold anymore.
In your case, you are regenerating int z everytime the loop is called,
All you have to do is define z outside the loop and instantiate z as 1 and also, you are not retaining the previous values of z so that's why it wasn't working. So it should be z = z + j and put this line below the print statement and you are done.
Here is an snippet of code which would help you my way:
int j = 1;
for(int i=1; i<=numberOfElements; i++) {
System.out.println(j);
j = j + 2*i;
}
And, here is an snippet of code which would help you your way:
int j = 0;
int z = 1;
for (int i = 1; i <= numberOfElements; i++)
{
j = i * 2; // + by how much
System.out.print(z + " ");
z = z + j; //sum
}
Note the trend.
You are adding a multiple of 2 to the previous number to get the next number. The multiple of 2 to be added depends upon the position of the number. For example, to get the 1st number, you add 2 x 0 to 1. To get the 2nd number, you add 2 x 1 to the previous number (that gives 3). To get the 3rd number, you add 2 x 2 to the previous number (that gives 7). To get the 4th number, you add 2 x 3 to the previous number (that gives 13).
To get the number at nth position, you add 2 x (n-1) to the previous number.
Now take a look at the example below, keeping the above explanation in mind.
public static void printSeparatorSequence(int numberOfElements) {
int number = 1;
for (int i = 0; i<numberOfElements;i++) {
number = number + 2 * i;
System.out.print(number);
}
System.out.println();
} //end of method printSeparatorSequence
} // end of class
This is the solution of your problem. I have discussed the code by the comment lines given within the code.
public class DistanceSeparator
{
/* Main Method */
public static void main(String[] args)
{
/* printSeparatorSequence Function is Called */
printSeparatorSequence(3);
printSeparatorSequence(5);
printSeparatorSequence(8);
}
/* printSeparatorSequence Function Definition */
public static void printSeparatorSequence(int NumberOfElements)
{
/* variable j is used to get the multiples of
2 by multiplying with variable i within the for loop
and variable sum is used to get the total value */
int j=2,sum=1;
for(int i=0;i<NumberOfElements;i++)
{
sum=sum+(j*i);
/* Here total sum is printed with a space */
System.out.print(sum+" ");
}
/* It is used for new line */
System.out.println();
}
}
I need to produce a triangle as shown:
1
22
333
4444
55555
and my code is:
int i, j;
for(i = 1; i <= 5; i++)
{
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
Producing a triangle the opposite way
1
22
333
4444
55555
What do i need to do to my code to make it face the right way?
You need 3 for loops:
Upper-level loop for the actual number to be repeated and printed
first inner level for printing the spaces
second inner level for to print the number repeatedly
at the end of the Upper-level loop print new line
Code:
public void printReversedTriangle(int num)
{
for(int i=0; i<=num; i++)
{
for(int j=num-i; j>0; j--)
{
System.out.print(" ");
}
for(int z=0; z<i; z++)
{
System.out.print(i);
}
System.out.println();
}
}
Output:
1
22
333
4444
55555
666666
I came across this problem in my AP CS class. I think you may be starting to learn how to program so heres what I'd do without giving you the answer.
Use a loop which removes the number of spaces each iteration. The first time through you would want to print four spaces then print 1 one time(probably done in a separate loop).
Next time through one less space, but print i one more time.
You need to print some spaces. There is a relation between the number of spaces you need and the number (i) you're printing. You can print X number of spaces using :
for (int k = 0; k < numSpaces; k++)
{
System.out.print(" ");
}
So in your code:
int i, j;
for(i = 1; i <= 5; i++)
{
// Determine number of spaces needed
// print spaces
for(j = 1; j <= i; j++)
{
System.out.print(i);
}
System.out.print("\n");
}
use this code ,
int i, j,z;
boolean repeat = false;
for (i = 1; i <= 5; i++) {
repeat = true;
for (j = 1; j <= i; j++) {
if(repeat){
z = i;
repeat = false;
while(z<5){
System.out.print(" ");
z++;
}
}
System.out.print(i);
}
{
System.out.print("\n");
}
}
You can use this:
int i, j;
int size = 5;
for (i = 1; i <= size; i++) {
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
for (j = 1; j <= i; j++) {
System.out.print(i);
}
System.out.print("\n");
}
This line:
if (i < size) System.out.printf("%"+(size-i)+"s", " ");
Is going to print the left spaces.
It uses the old printf with a fixed sized string like 5 characters: %5s
Try it here: http://ideone.com/jAQk67
i'm having trouble sometimes as well when it's about formatting on console...
...i usually extract that problem into a separate method...
all about how to create the numbers and spacing has been posted already, so this might be overkill ^^
/**
* creates a String of the inputted number with leading spaces
* #param number the number to be formatted
* #param length the length of the returned string
* #return a String of the number with the size length
*/
static String formatNumber(int number, int length){
String numberFormatted = ""+number; //start with the number
do{
numberFormatted = " "+numberFormatted; //add spaces in front of
}while(numberFormatted.length()<length); //until it reaches desired length
return formattedNumber;
}
that example can be easily modified to be used even for Strings or whatever ^^
Use three loops and it will produce your required output:
for (int i=1;i<6 ;i++ )
{
for(int j=5;j>i;j--)
{
System.out.print(" ");
}
for(int k=0;k<i;k++)
{
System.out.print(i);
}
System.out.print("\n");
}
Your code does not produce the opposite, because the opposite would mean that you have spaces but on the right side. The right side of your output is simply empty, making you think you have the opposite. You need to include spaces in order to form the shape you want.
Try this:
public class Test{
public static void main (String [] args){
for(int line = 1; line <= 5; line++){
//i decreases with every loop since number of spaces
//is decreasing
for(int i =-1*line +5; i>=1; i--){
System.out.print(" ");
}
//j increases with every loop since number of numbers
//is decreasing
for(int j = 1; j <= line; j++){
System.out.print(line);
}
//End of loop, start a new line
System.out.println();
}
}
}
You approached the problem correctly, by starting with the number of lines. Next you have to make a relation between the number of lines (the first for loop) and the for loops inside. When you want to do that remember this formula:
Rate of change*line + X = number of elements on line
You calculate rate of change by seeing how the number of elements change after each line. For example on the first line you have 4 spaces, on the second line you have 3 spaces. You do 3 - 4 = -1, in other words with each line you move to, the number of spaces is decreasing by 1. Now pick a line, let's say second line. By using the formula you will have
-1(rate of change) * 2(line) + X = 3(how many spaces you have on the line you picked).
You get X = 5, and there you go you have your formula which you can use in your code as you can see on line 4 in the for loop.
for(int i = -1 * line +5; i >= 1; i--)
You do the same for the amount of numbers on each line, but since rate of change is 1 i.e with every line the amount of numbers is increasing by 1, X will be 0 since the number of elements is equal to the line number.
for(int j = 1; j <= line; j++){
For my homework i'm supposed to use '*' to make a picture prescribed in the notes. Basically what I would like help with is how to use subtraction in a for loop.
My code:
public class Starshapesver2{
public static void main(String[] args){
star(31) ;
System.out.println(); //I initialize 'star' and 'space' later on
for(int i=1; i<=7; i=i+1){
star(14);
blank(5);
star(14);
}
...
basically how would I add 4 to 'blank' and subtract 4 from 'spaces' inside the for loop
(and so that it would keep adding on so the first blank would be 4 then 8 then 12 and so on)
sorry if this is confusing
are you expecting something like below
for(int i=1,increment=4; i<=7; i=i+1,increment=increment+4)
{
star(14 - increment);
blank(5 + increment);
star(14 - increment);
}
If I understand correctly, you want to have the arguments you pass to star() and blank() change each time through the loop. So you need to make them variables. Declare them outside of the loop, and modify them with each pass. Something like this:
int numBlanks = 5;
for (int i = 0; i <= 7; i++) {
blanks(numBlanks);
numBlanks = numBlanks + 4; // numBlanks will increase by 4 each time through the loop
}
I assume you want to continually add 4 to blank and subtract 4 from Spaces until the loop ends. Well you can do this:
public static void main(String[] args)
{
star(31) ;System.out.println(); //I initialize 'star' and 'space' later on
int Blankint = 5;
int spacesint =4// i cannot see your spaces in the code
for(int i=1; i<=7; i=i+1)
{
Star(14);
blank(5+Blankint);
Blankint =Blankint+4;
spaces(20 - spacesint); //assuming this where your space is because you didnt indicated it above.
spacesint = spacesint+4;
star(14);
}
}
With this code your blank increments evert loop adding 4 to blanks and subtracting 4 to spaces
So if your initial blank is 5 next would be 9 then after the loop it would be 13 etc etc.
Assuming you mean: "How would I add 4 to blank and substract 4 from spaces each iteration". At the same time assuming that these are methods which take an int.
for(int i=1; i<=7; i=i+1)
{
star(14);
//Make the call with the starting 5 adding i * 4 which varies each iteration
blank(5 + i * 4);
star(14);
}
You didn't show spaces in the loop itself but assuming it is there it could look like:
spaces(startingNumber - i * 4);