Click here to Skip to main content
15,887,135 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i need to print out two String variables using the toString method, and what ive tried it won't print out right and it wont compile.

What I have tried:

Java
public String toString(){
         this.dayOfTheWeek = day;
         this.name = n;
         String day = new String("The name of the show is: " + n + "and airs on: " + day);
         System.out.println(day.toString());
Posted
Updated 15-Mar-16 0:42am
v2

1 solution

This is all wrong I'm afraid. The variables day and n do not exist in the toString method. They should be set either in the constructor:
Java
class ThisClass {
    private int dayOfTheWeek;
    private String name;

    ThisClass(int day, String name) {
         this.dayOfTheWeek = day;
         this.name = name;
    }

or by using setters (see Adding Setter and Getter Methods - The Java EE 6 Tutorial[^]).

Also you should not be printing the data in the toString method. Its purpose is to return a string which may be printed by the caller. So Your method should look like:
Java
public String toString(){
    String textday = new String("The name of the show is: " + n + "and airs on: " + day);
    return textday;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900