Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My method isn't working although no error messages are shown

I need to write a method that needs to output a certain string an amount of times that equals to a variable in the main class. I wrote it with the for loop but it isn’t outputting anything nor is it showing any errors. (method must contain local variable)
`public class main {

public static void main(String[] args) {
    DateFirstTry date1, date2;
    date1 = new DateFirstTry();
    date2 = new DateFirstTry();

    // Date1 declaration
    date1.month = "December";
    date1.day = 31;
    date1.year = 2012;

// Date2 declaration
    date2.month = "July";
    date2.day = 4;
    date2.year = 1776;

// Assigment
    date2.happyGreetings();
    
public class DateFirstTry {
    public String month;
    public int day;
    public int year; //a four digit number.
    public void writeOutput() {
        System.out.println(month + " " + day + ", " + year);
    
    }
    public void makeItNewYears() {
        this.month = "January";
        this.day = 1;
    }

    public void happyGreetings() {
        for (int i = 0; i==this.day; i++ ) {
            System.out.println("Happy Greetings!");
        }
    }
    public void getNextYear() {
    
        System.out.println(this.year + 1);
    }
    
    public void yellIfNewYears() {
        if (month.equals("January") && day == 1)
            System.out.println("Hurray!");
    else 
        System.out.println("Its not new year!");
    }
}

I tried to create a do-while-loop but I couldn’t complete it, and I tried some minor adjustments to the for loop, but none worked.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It looks like a mistake in loop condition. It will be executed while i == this.day. In this case ‘day’ equals 4 and ‘i’ equals 0. So, this condition is always false and loop body is never executed

    for (int i = 0; i==this.day; i++ ) {
        System.out.println("Happy Greetings!");
    }

If you want loop to be executed as many times as value in ‘this.day’, then you should write it like this:

    for (int i = 0; i < this.day; i++) {
        System.out.println("Happy Greetings!");
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading