Java Java Objects Meet Objects Final

Asaf ahmed
Asaf ahmed
461 Points

cant find out whats wrong with my program. 9 errors.

public class Example {

public static void main(String[] args) { // Your amazing code goes here... System.out.println("we are making a new pen dispenser"); newPen dispenser = new newPen("yoda"); System.out.printf(" the dispenser is %s %n", dispenser.getCharacterName()); } String before = dispenser.swapHead(" Darth Vader"); System.out.printf( " it was %s but chris switched it to %s %n", before, dispenser.getCharacterName());

} class newPen { private String characterName;

public newPen(String characterName){ this.characterName=characterName;}

public String getCharacterName() { return characterName;

} public String swapHead(String characterName) {

String originalCharacterName = this.characterName; this.characterName = characterName; retrun originalCharacterName; }

}

1 Answer

Brendon Butler
Brendon Butler
4,241 Points

After reformatting your code, I added comments for any issues I noticed.

public class Example {
    public static void main(String[] args) {
        System.out.println("we are making a new pen dispenser");
        newPen dispenser = new newPen("yoda");
        System.out.printf(" the dispenser is %s %n", dispenser.getCharacterName());
    }

    // these 2 lines should be within the main method body ^
    String before = dispenser.swapHead(" Darth Vader"); 
    System.out.printf( " it was %s but chris switched it to %s %n", before, dispenser.getCharacterName());
}

class newPen { // class names should start with a capital letter and be a noun (see #1)
    private String characterName;

    public newPen(String characterName) {
        this.characterName = characterName;
    }

    public String getCharacterName() {
        return characterName;
    }

    public String swapHead(String characterName) {
        String originalCharacterName = this.characterName;
        this.characterName = characterName;
        retrun originalCharacterName; // misspelling on the word "return"
    }
}

#1 Class Naming Conventions - When creating a new class, the name of the class should always start with a capital and be camelcase (see code conventions). Your class name looks to me like it should be a method name, as it's an action (create new pen). Instead, your class should be named "Pen," since you're creating a pen object. When renaming, make sure to change the name of your class file as well. (newPen.class should be Pen.class)

There may be more issues, but without seeing your stacktrace (or testing on my own), this is all I've noticed so far. Hope this helps get you started.