编译错误:预期的标识符

时间:2011-12-15 13:00:07

标签: java

import java.io.*;

public class details
{
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("What is your name?");
    String name = in.readLine(); ;
    System.out.println("Hello " + name);
}

我的代码问题是我在编译时得到“标识符” 任何人都可以帮我做什么? 或者更好,任何人都可以提供使用BufferedReader提示名称,地址和年龄的代码,然后最终显示输出..

谢谢!

4 个答案:

答案 0 :(得分:22)

您尚未定义代码周围的方法。

import java.io.*;

public class details
{
    public static void main( String[] args )
    {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

在这种情况下,我假设您希望您的代码在类的main方法中执行。当然,这个代码可能采用任何其他方法。

答案 1 :(得分:9)

必须 将以下代码包装到一个块中(无论是方法还是静态)。

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);

如果没有块,您只能声明变量,而不是在单个语句中为它们赋值。

方法main()现在是最佳选择:

public class details {
    public static void main(String[] args){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

或者如果你想使用静态块那么......

public class details {
    static {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

或者如果你想构建另一种方法,那么..

public class details {
    public static void main(String[] args){
        myMethod();
    }
    private static void myMethod(){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

还要担心BufferedReader导致的异常。

答案 2 :(得分:1)

您还必须捕获或抛出IOException。见下文。并不总是最好的方式,但它会得到一个结果:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

答案 3 :(得分:0)

只有变量/对象声明语句写在方法

之外
public class details{
    public static void main(String arg[]){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

这里是示例尝试学习java书籍并查看语法然后尝试开发程序