Java编译器错误:"public type ..必须在自己的文件中定义"?

7 java compiler-errors

我想编译这个:

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]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我使用了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)
Run Code Online (Sandbox Code Playgroud)

我以前从未编译/完成过Java.我只需要这个来测试我的其他程序结果.有任何想法吗?我正在Linux机器上编译.

Ree*_*ore 15

需要调用该文件DNSLookUp.java,您需要将:

import java.net.InetAddress;
import java.net.UnknownHostException;    
Run Code Online (Sandbox Code Playgroud)

在文件的顶部


Cur*_*Dog 5

这里给出的答案都是好的,但是考虑到这些错误的性质以及本着“教人钓鱼等”的精神:

  1. 安装选择的IDE(Netbeans是一个简单的开始)
  2. 将代码设置为新项目
  3. 单击发生错误的行上的灯泡
  4. 选择您想要的修复
  5. 惊叹于现有工具的强大功能