Wrong amount of lines in printTriangle? - java

I've been doing a MOOC.fi Java course and it comes along quite well, except the Christmas Tree part. It works as intended in the output, but the system won't accept it and I don't know why.
I get this error:
when printTriangle(1) was called, wrong amount of lines was printed expected:<1> but was:<2>
Here's the code:
public class AdvancedAstrology {
public static void printStars(int number) {
for(int i = 0; i < number; i++){
System.out.print("*");
}
System.out.println();
}
public static void printSpaces(int number) {
while(number > 0){
System.out.print(' ');
number--;
}
}
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++);
}
}
public static void christmasTree(int height) {
int h = height -1;
int stand = height - 2;
int s = 1;
while(height > 0){
printSpaces(h);
printStars(s);
s+=2;
h--;
height--;
}
printSpaces(stand);
printStars(3);
printSpaces(stand);
printStars(3);
}
public static void main(String[] args) {
// The tests are not checking the main, so you can modify it freely.
printTriangle(5);
System.out.println("---");
christmasTree(4);
System.out.println("---");
christmasTree(10);
}
}

You're doing post increment, that's why in star is being passed as 0 in first iteration.
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++); //Here. change it to ++star
}
}

Related

How to print numbers from 1 to n using recrsion in java

public static void increase(int N){
int a = 1;
if(b <= N) {
System.out.print(a + " ");
a++;
} else {
increase(N);
}
}
I can see the problem with this approach that the int a gets initialized to 1 every time the code goes for a recursive call. Can anyone suggest the correct solution?
public static void main(String[] args) {
increase(10,1);
}
private static void increase(int N,int begin){
if(begin <= N){
System.out.print(begin+" ");
begin=begin+1;
increase(N,begin);
}
return;
}
You have to create one additional private method to count current value.
public static void increase(int N) {
increase(1, N);
}
private static void increase(int a, int N) {
if (a <= N) {
if (a > 1)
System.out.print(' ');
System.out.print(i);
increase(a + 1, N);
}
}
You can just put a outside the function:
// I don't know your class
private a = 1;
static void increase(int N){
int a = 1;
if(b <= N){
System.out.print(a+" ");
a=a+1;
}
else
{
increase(N);
}
}
static void increase(int N, int a){
if (a>N) return;
System.out.print(a+" ");
a=a+1;
increase(N,a);
}
//example call from static context print 1-100
increase(100,1);

are there any fresh ideas for a recursive function printing square pattern?

i have a question where i need to do a recursive function getting int and doing star pattern of a square like if i insert 4 into the function it will give me:
****
****
****
****
so i made this recursion and i want to shrink my idea into one function what can you suggest to improve my design, thanks.
static int count = 0;
public static void rect(int num){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
}
public static void SetCount(int num){
count = num;
rect(num);
}
public static void main(String[] args) {
int i = 6;
SetCount(i);
}
You can eliminate the SetCount method and the second if check, something like this would work as well :
static int count = 0;
public static void rect(int num) {
if (count <= 0)
return;
for (int i = 0; i < num; i++) {
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
public static void main(String[] args) {
count = 4;
rect(count);
}
One argument, the size of the square. No external variables:
class Homework {
public static void square(int side) {
if (side > 0) {
for (int i = 0; i < side; i++) {
square(-side);
}
} else if (side < 0) {
System.out.print('*');
square(side + 1);
} else {
System.out.println();
}
}
public static void main(String[] args) {
square(5);
}
}
Your solution, and others offered so far, are all recursive on the rows of the square and iterative on the columns. This solution inverts that -- it's recursive on the columns and iterative on the rows.
OUTPUT
> java Homework
*****
*****
*****
*****
*****
>
import java.util.*;
import java.lang.*;
import java.io.*;
class Check{
static void rect(int num,int count){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num,count);
}
}
public static void main(String[] args) {
int i = 6;
rect(i,i);
}
}
Instead of using a class variable count and setting it again and again. Use two paramters for the recursive function. "num" to print stars num times in a single row and "count" to keep track of number of rows.

printStars method with recursion

Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****
This is what I did so far:
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
System.out.println("");
}
else{
System.out.print("*");
printStars(count-1);
}
}
}
My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.
This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
public static void main(String[] args) {
System.out.println(star(4, new StringBuilder()));
}
public static StringBuilder star(int times, StringBuilder builder) {
return getStars(times, builder, times);
}
public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
if (currentIteration < -1 * times) return builder;
else if (currentIteration != 0) {
builder.append(getNTimes(Math.abs(currentIteration)));
return getStars(currentIteration - 1, builder, times);
} else {
return getStars(currentIteration - 1, builder, times);
}
}
public static String getNTimes(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append("*");
}
return builder.append("\n").toString();
}
}
Your program is incorrect, see the below program and analyze it -
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
// System.out.println("");
}
else{
int tempCount = count;
while(tempCount>0){
System.out.print("*");
tempCount--;
}
System.out.println();
printStars(count-1);
while(tempCount<count){
System.out.print("*");
tempCount++;
}
System.out.println();
}
}
}
Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.
Try this
public static void printStars(int count){
if (count == 0){
return;
}
printStarNTimes(count);
printStars(count-1);
printStarNTimes(count);
}
private static void printStarNTimes(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
Logic is in printing star count times in the current call and when the recursive call returns.
The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){
printStars(count, count, -1);
}
public static void printStars(int count , int max, int increment){
for(int i =0; i< count; i++) {
System.out.print("*");
}
count += increment;
if(count ==0 ) { //lower limit reached
increment = -increment;
}else {
System.out.println("");
}
if (count > max){ //upper limit reached
return;
}
printStars(count, max, increment);
}

How to fix java error?

So I have to create a program where I use polymorphism and inheritance to create arrows that point left and arrow and I did that. however, when I created my main class and try to invoke the methods, say for example "LeftArrow.drawHere" to draw the arrow i get errors saying I cannot make a static reference to the non static field "drawHere() from the class LeftArrow". I was wondering then if I can't do that how can I design my main method so it draws the arrows?
here is my code, note that there are several classes but I will post all of them here.
import java.util.Scanner;
public class LeftArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public LeftArrow()
{
super();
tail = 0;
width = 0;
}
public LeftArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth);
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
//System.out.println();
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset());
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside + 1));
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawTail()
{
skipSpaces(getOffset() - getInside() - 1);
System.out.print('*');
skipSpaces(getInside());
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() - (inside - 1));
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset());
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
#Override
public void setOffset(int noff) {
// TODO Auto-generated method stub
}
#Override
public int getOffset() {
// TODO Auto-generated method stub
return 0;
}
}
import java.util.Scanner;
public class RightArrow extends ShapeBasic
{
private int tail, width;
private static int inside;
public RightArrow()
{
super();
tail = 0;
width = 0;
}
public RightArrow(int noff, int ntail, int nwidth)
{
super(noff);
tail = ntail;
setWidth(nwidth); // must be odd
}
public void setTail(int ntail)
{
tail = ntail;
}
public int getTail()
{
return tail;
}
public void setWidth(int nwidth)
{
if (nwidth % 2 == 1)
{
width = nwidth;
}
else
{
System.out.println(" Width must be odd");
System.out.println("Enter a new width");
Scanner key = new Scanner(System.in);
int wid = key.nextInt();
setWidth(wid);
}
}
public int getWidth()
{
return width;
}
public void drawHere()
{
drawTriangle();
drawTail();
drawBTriangle();
System.out.println();
}
public void drawTail()
{
skipSpaces(getOffset() + 1);
for (int count = 0; count < tail ; count++)
{
System.out.print('*');
}
skipSpaces(getInside());
System.out.print('*'); // fix
}
public void drawTriangle()
{
inside = 1;
int split = (width/2);
skipSpaces(getOffset() + tail);
System.out.println('*');
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
skipSpaces(inside);
System.out.print('*');
inside = inside + 2;
System.out.println();
}
}
public void drawBTriangle()
{
int inside = getInside();
int split = (width/2);
System.out.println();
for(int count = 0; count < split; count ++)
{
skipSpaces(getOffset() + tail);
System.out.print('*');
inside = inside - 2;
skipSpaces(inside);
System.out.print('*');
System.out.println();
}
skipSpaces(getOffset() + tail);
System.out.print('*');
}
public int getInside()
{
return inside;
}
private static void skipSpaces(int number)
{
for (int count = 0; count < number; count++)
System.out.print(' ');
}
}
public abstract class ShapeBase implements ShapeInterface {
private int offset;
public abstract void drawHere();
public void drawAt(int lineNumber) {
for (int count = 0; count < lineNumber; count++)
System.out.println();
drawHere();
}
}
public class ShapeBasic implements ShapeInterface
{
private int offset;
public ShapeBasic()
{
offset = 0;
}
public ShapeBasic( int noff)
{
offset = noff;
}
public void setOffset(int noff)
{
offset = noff;
}
public int getOffset()
{
return offset;
}
public void drawAt(int linnumber)
{
for (int count = 0; count < linnumber; count++)
System.out.println();
drawHere();
}
public void drawHere()
{
for (int count = 0; count < offset; count++)
System.out.print(' ');
System.out.println('*');
}
}
public interface ShapeInterface
{
public void setOffset(int noff); // set how many space from left
public int getOffset(); // returns offset
public void drawAt(int linnumber); // moves down equal to line number Ex. 5 = 5 down
public void drawHere(); // draws shape after moving left equal to offset
}
I'd ask to see your main method, but I don't have the reputation.
At a guess, I'd say maybe you are not actually instantiating objects of these classes in your main method, but trying to call the methods from them. If, for instance, you do this:
LeftArrow lArrow = new LeftArrow();
lArrow.drawHere();
it should work.
The method drawHere is declared as non-static. Instead of LeftArrow.drawHere() you should call
LeftArrow left = new LefArrow(a, b, c);
left.drawHere();
main is static. It needs to create instances of LeftArrow before it can use them. Something like this:
LeftArrow myArrow = new LeftArrow();
myArrow.drawHere();

Number pyramind, with recursive method. Java Beginner

I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :).
You need to implement two recursive functions:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner":
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
You could do it like this:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}

Categories