Java编译器错误:“public type ..必须在自己的文件中定义”?
我想编译这个:
public class DNSLookUp { public static void main(String[] args) { InetAddress hostAddress; try { hostAddress = InetAddress.getByName(args[0]); System.out.println (hostAddress.getHostAddress()); } catch (UnknownHostException uhe) { System.err.println("Unknown host: " + args[0]); } } }
我使用了javac dns.java,但是我得到了一堆错误:
dns.java:1: error: The public type DNSLookUp must be defined in its own file public class DNSLookUp { ^^^^^^^^^ dns.java:3: error: InetAddress cannot be resolved to a type InetAddress hostAddress; ^^^^^^^^^^^ dns.java:6: error: InetAddress cannot be resolved hostAddress = InetAddress.getByName(args[0]); ^^^^^^^^^^^ dns.java:9: error: UnknownHostException cannot be resolved to a type catch (UnknownHostException uhe) { ^^^^^^^^^^^^^^^^^^^^ 4 problems (4 errors)
我以前从未编译/完成过Java。 我只需要这个来测试我的其他程序结果。 有任何想法吗? 我正在Linux机器上编译。
该文件需要被称为DNSLookUp.java
,您需要将:
import java.net.InetAddress; import java.net.UnknownHostException;
在文件的顶部
将文件重命名为DNSLookUp.java
并导入适当的类。
import java.net.InetAddress; import java.net.UnknownHostException; public class DNSLookUp { public static void main(String[] args) { InetAddress hostAddress; try { hostAddress = InetAddress.getByName(args[0]); System.out.println(hostAddress.getHostAddress()); } catch (UnknownHostException uhe) { System.err.println("Unknown host: " + args[0]); } } }
这里给出的答案都很好,但鉴于这些错误的性质以及“教人钓鱼等等”的精神:
- 安装首选IDE(Netbeans很容易入手)
- 将代码设置为新项目
- 单击发生错误的行上的灯泡
- 选择您想要的修复程序
- 惊叹于您可用的工具的力量
您需要导入正在使用的类。 例如:
import java.net。*;
从java.net包导入所有类。
您也不能在名为dns.java的文件中使用公共类DNSLookUp。 看起来是Java教程的时候了……