Nicholas Dry
Nicholas Dry

Reputation: 117

How to change the placeholder text in a string from 'null' in java

My code compiles and runs how I want it to, however, I have a question, after I am done adding events in the calendar, unless there was a specific event for that day, the result that comes to terminal shows that for each day there is nothing the result is 'null' I was wondering if there was any way I could change that

public class Calendar {
public static void main(String[] args) {

    String[] calender = new String[32];
    String ans = " ";

    do {
        System.out.print("Type the number day of your event: ");
        int date = IO.readInt();
        System.out.println("What is the event?");
        String event = IO.readString();
        System.out.println("Do you have another event to add? y/n: ");
        addEvent(calender, event, date);
        ans = IO.readString();
    } while (ans.equals("y"));

    printCal(calender);


}

public static void addEvent(String[] calender, String event, int date) {

    calender[date] = event;

    // return true;

}

public static void printCal(String[] calender) {
    for (int i=1;i<calender.length;i++) {
        System.out.println("Day: " + i + " " + " Event: " + calender[i]);
    }
}

}

Terminal Result

Upvotes: 1

Views: 1211

Answers (2)

Konstantin Neradovsky
Konstantin Neradovsky

Reputation: 11

If you're using java8 you can employ Optional class to set the placeholder:

public static void addEvent(String[] calender, String event, int date) {

    calender[date] = Optional.ofNullable(event).orElse("placeholder");

    // return true;

}

Upvotes: 1

JDrost1818
JDrost1818

Reputation: 1126

While printing you can check if it is null and if it is, print something else. In this case, it will print "Holding Text" instead of null. Feel free to change it to whatever you want.

public static void printCal(String[] calender) {
    for (int i=1;i<calender.length;i++) {
        String event = (calendar[i] == null) ? "Holding Text" : calendar[i];
        System.out.println("Day: " + i + " " + " Event: " + event);
    }
}

Upvotes: 3

Related Questions