令牌错误,语法

时间:2013-12-06 14:58:33

标签: java syntax

我正在用Java编写一个函数,但我无法编译代码。我没有看到语法错误;你能救我吗?

public String getUserInput(String prompt){
    String inputLine = null;
    System.out.print(prompt + " ");
    try(
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        inputLine = is.readLine();
        if (inputLine.length() == 0 ) 
            return null;
        ) 
    catch (IOException e) {
            System.out.println("IOException: " + e);
        }
    return inputLine.toLowerCase();
}

它无法编译。

3 个答案:

答案 0 :(得分:3)

()替换为try - 阻止{}

答案 1 :(得分:2)

检查try块括号,其()在java中是不允许的,并为方法保留。对于块使用{}

正确答案

public String getUserInput(String prompt){
    String inputLine = null;
    System.out.print(prompt + " ");
    try
    //( this is wrong
    {
        BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
        inputLine = is.readLine();
        if (inputLine.length() == 0 ) 
            return null;
        //)
    } 
    catch (IOException e) {
            System.out.println("IOException: " + e);
        }
return inputLine.toLowerCase();
}

答案 2 :(得分:1)

您是否想要try-with-resource(Java 7 +)?

try (BufferedReader is = new BufferedReader(new InputStreamReader(System.in))) {

    inputLine = is.readLine();

    if (inputLine.length() == 0)
        return null;

} catch (IOException e) {
    System.out.println("IOException: " + e);
}

如果没有,那么请回想一下标准try-catch块采用以下形式:

try {
    ...
} catch (...) {

}

请注意{}括号。