Error: expected {when creating a class

0

I wrote the code below but it is giving me the error

  

Expected {

After my class declaration

public class book(string title, string text){
    string _title = title;
    string _text = text;

    void NewTitle (book livro, string newtitle){
    livro._title = newtitle;
    }

    string BookTitle (book livro){
    return livro._title;
    }

    string BookText (book livro){
    return livro._text; 
   }

    int BookLength (book livro){
    return (livro._title.length + livro._text.length);
   }

    boolean samebook(book livro1, book livro2){
        return (livro1._title == livro2._title && livro1._text == livro2._text);
   }

}
    
asked by anonymous 28.09.2015 / 23:33

1 answer

6

The most obvious mistake you are making is putting a list of parameters in a class. Class is not method. Java does not have the primary constructor feature (exists in Kotlin and there is #

You will actually have to create a builder to do what you want. It looks like you merged the syntax of the class with that of the constructor. Then you have to create the instance variables to be used by these methods.

But there are other errors. The type of text in Java is String and can not be written in lower case. To know what size the text has, it calls the length() method. It is not a property, as it is in other languages.

samebook (bad name) should probably be static .

It is not common in Java to use _ in variable names. The methods are usually tiny. Some of this methods are called getters and stters . Do not use the class name in the method name unless you have a very good reason for this, this is redundant. Example of what would be best: setTitle() , getTitle() , getText() and length() . And the class name is usually capitalized. It's not a bug, of course.

There are some other things that in real code may not be quite what I should do, but it seems to me an exercise and this does not influence. I do not even know what the requirements are.

Then it would look like this:

class Book {
    private String _title;
    private String _text;

    Book(String title, String text) {
        _title = title;
        _text = text;
    }
    void NewTitle(Book livro, String newtitle) {
        livro._title = newtitle;
    }

    String BookTitle(Book livro) {
        return livro._title;
    }

    String BookText(Book livro) {
        return livro._text; 
    }

    int BookLength(Book livro) {
        return (livro._title.length() + livro._text.length());
    }

    boolean samebook(Book livro1, Book livro2){
        return (livro1._title == livro2._title && livro1._text == livro2._text);
    }
}
    
29.09.2015 / 17:09