-1

I am wondering why I cannot simply do this

System.out.println("Today: " + todayDatetime.display());

The method is

    public void display() {

     System.out.println(month + "/" + day + " " + hours + ":" + minutes + ":" + seconds);


}

I would like to have my method and text on the same line. Is there a possible way to turn it into a string maybe so I can have it print?

paisanco
  • 4,098
  • 6
  • 27
  • 33
  • 1
    If you want the text and result in one line then use System.out.print() method instead of println(). – Mr. Roshan Dec 02 '17 at 04:10
  • Possible duplicate of [How can I print to the same line?](https://stackoverflow.com/questions/7939802/how-can-i-print-to-the-same-line) – Jamsheer Dec 02 '17 at 04:37

2 Answers2

1

First, don't berate yourself! Programming can be challenging to learn. Lets take it step by step.

 public void display() {

     System.out.println("Today: " + month + "/" + day + " " + hours + ":" + minutes + ":" + 
     seconds);


 }

To call it, you would write:

 display();

In your code.

Alternatively,

You could write:

 public String display(){
      return month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
 }

And you would then call the method as you originally tried(provided there are no syntax errors).

If it needs to be on the same line make sure you use either print(); or only a single println();

King Twix
  • 52
  • 8
0

Because display() is void, it doesn't return anything. Thus you cannot add it to a String for display. But you don't need to. You can do something like,

System.out.print("Today: ");
todayDatetime.display();

Alternatively, change display to return a String like

public String display() {
    return month + "/" + day + " " + hours + ":" + minutes + ":" + seconds;
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249