2017-02-21 261 views
0

我目前正在运行一个Java教程,现在主要关注包和受保护的变量。我应该编译一个例子,说明在使用多个包时代码是如何工作的。出于某种原因,我完全无法获得编译的代码。我甚至尝试复制粘贴教程中的演示代码,甚至无法编译。我自己的代码和教程代码抛出:java error:class,interface,or enum expected(multiole packages)

java 23: error: class, interface, or enum expected 
package bookpackext; 
^ 
1 error 

任何人都能够看到这里有什么问题吗?我一直在四处张望,每个发布了相同错误的人都被告知要仔细检查卷发和方法,但我不能在我的生活中看到任何错误。

在此先感谢! 我自己的代码如下:

package bookpack; 

public class Book { 
    protected String title; 
    protected String author; 
    protected int pubDate; 

    public Book(String t, String a, int d) { 
     title = t; 
     author = a; 
     pubDate = d; 
    } 

    public void show() { 
     System.out.println(); 
     System.out.println(title); 
     System.out.println(author); 
     System.out.println(pubDate); 
     System.out.println(); 
    } 
} 

package bookpackext; 

class ExtBook extends bookpack.Book { 
    private String publisher; 

    public ExtBook(String t, String a, int d, String p) { 
     super(t, a, d); 
     publisher = p; 
    } 

    public void show() { 
     super.show(); 
     System.out.println(publisher); 
     System.out.println(); 
    } 

    public String getPublisher() {return publisher;} 
    public void setPublisher(String p) {publisher = p;} 
    public String getTitle() {return title;} 
    public void setTitle(String t) {title = t;} 
    public String getAuthor() {return author;} 
    public void setAuthor(String a) {author = a;} 
    public int getPubDate() {return pubDate;} 
    public void setPubDate(int d) {pubDate = d;} 
} 

class ProtectDemo { 
    public static void main(String args[]) { 
     ExtBook books[] = new ExtBook[5]; 

     books[0] = new ExtBook("Book 1", "Author 1", 2013, "Publisher 1"); 
     books[1] = new ExtBook("Book 2", "Author 2", 2014, "Publisher 2"); 
     books[2] = new ExtBook("Book 3", "Author 3", 2015, "Publisher 3"); 
     books[3] = new ExtBook("Book 4", "Author 4", 2016, "Publisher 4"); 
     books[4] = new ExtBook("Book 5", "Author 3", 2017, "Publisher 5"); 

     for(int i = 0; i < books.length; i++) 
      books[i].show(); 

     System.out.println("Showing all books by Author 3:"); 
     for(int i = 0; i<books.length; i++) 
      if(books[i].getAuthor() == "Author 3") 
       System.out.println(books[i].getTitle()); 
    } 
} 
+0

什么是java文件的文件名? – SaWo

+2

你是否有机会将它全部粘贴到单个java文件中?包旨在分离文件。 – Arqan

+0

做什么@DaveNewton说。另外,请确保软件包名称实际上反映了您的源文件所在的目录。 – ostrichofevil

回答

5

你不能把多个package声明在一个文件中。

https://docs.oracle.com/javase/tutorial/java/package/createpkgs.html

The package statement (for example, package graphics;) must be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.

注意,错误消息查明这行,说什么是错的。从任何语言开始时,请确保您有一本语言参考指南,方便使用–,这样可以节省大量时间。

+0

非常感谢!该教程实际上将两个包都包含在一个文件中。无论如何,问题都解决了。干杯! – Runlos