java缺少字段

时间:2015-02-07 06:47:06

标签: java field

public static void main(String[] args) {
    // create a book named "Java is Fun" with 200 in stock costing 55.00 each.  The stock number is 1234
    Book javafun = new Book("Java is Fun", 200, 55.00, 1234);
    //print out the book using the toString() method
    System.out.println (javafun.toString());

    //create a book calling the empty constructor.
    Book newbook2 = new Book();
    //set the title to "Databases R Us"
    String title = "Databases R Us";
    //set the number in stock to 50
    int numInStock = 50;
    // set the cost each to $35.00
    double cost = 35.00;  <------ this 
    // set the stock number to 5555
    int stockNum = 5555; 
    //print out the book.
    System.out.println(newbook2.toString());
    //change the price to $55.00
    double cost = 55.00;  <-- and this gives me duplicate error
    //print out the book
    System.out.println (newbook2.toString());

}

我将如何在空间下面执行这些步骤?

我做了我认为应该做的事,但它给了我重复。并且输出不正确

输出应该是:

Java很有趣,身份证号码1234有200本库存,每张售价55.00美元。

数据库R我们身份证号码5555有50本库存,每本35.00美元。

数据库R我们身份证号码5555有50本库存,每张售价55.00美元。

3 个答案:

答案 0 :(得分:1)

您有一个重复的局部变量。 double cost = 55.00;会导致语法错误。

根据程序中的注释判断,看起来您只想更改值,不要在变量名前加上数据类型。

即。 cost = 55.00;

如果您要更改与特定Book对象相关联的费用,则会像其他用户建议的那样..只需转到book1.setCost/Title/Whatever(...)我假设在您的Book类中您有setter方法和变量不公开。

答案 1 :(得分:1)

除了重复的变量创建之外,您需要的是将成员cost的值更改为55或50,它将是这样的。

// change the value of the cost member
newBook2.cost = 55;

现在,一旦你输出这个(用字符串表示法),你将得到书中的成本。到目前为止,您只是初始化新变量,而不是更改Book对象成员的值。假设您有一本书,并且您想要更改这些对象的属性,您可以像下面的代码那样进行,

// create the object
Book myBook = new Book();

// now we will change the values for the members
myBook.title = "Databases R Us";
myBook.numInStock = 50;
myBook.cost = 50;
myBook.stockNum = 5555;

// Above were the settings for the Book object
System.out.print(myBook.toString());

上面的代码将具有您为Book对象指定的属性,而不是变量的值。有关类成员的更多信息,请查看此Java开发人员的链接:http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

答案 2 :(得分:0)

public class BookDriver {

public static void main(String[] args) {
    // create a book named "Java is Fun" with 200 in stock costing 55.00 each.  The stock number is 1234
    Book javafun = new Book("Java is Fun", 200, 55.00, 1234);
    //print out the book using the toString() method
    System.out.println (javafun.toString());
    //create a book calling the empty constructor.
    Book newbook2 = new Book();

    //set the title to "Databases R Us"
    newbook2.setTitle("Databases R Us");
    //set the number in stock to 50
    newbook2.setNumInStock(50);
    // set the cost each to $35.00
    newbook2.setCost(35.00);
    // set the stock number to 5555
    newbook2.setStockNum(5555); 
    //print out the book.
    System.out.println(newbook2.toString());
    //change the price to $55.00
    newbook2.setCost(55.00);
    //print out the book
    System.out.println (newbook2.toString());