当我创建 class 时,我在 "try-catch" 块中收到 "illegal start of type" 错误

When I create a class, I receive "illegal start of type" error in "try-catch" block

class address
{

String address;
String newaddr = address.trim();
final int ziplength =4;
    String input;
    Scanner in = new Scanner(System.in);
    String temp = in.next();
    String zipcode = input.substring(input.length()-ziplength);

    try **//illegal start type error**
    {
        Integer.parseInt(zipcode);
        System.out.println("PO is: "+zipcode);    
    }
    catch( Exception e) **//illegal start type error**
    {
        System.err.println("Last 4 chars are not a number.");
    }
}

这段代码段从字符串中提取最后四个字符,看它们是否是post代码。

我在 NetBeans 中评论了报告点 "illegal start type error"。

请问,创建class时是否不能使用try-catch?或者,这个 class 是否遗漏了什么?

我尝试搜索计算器。但我仍然感到困惑。这里有一些链接。

Java illegal start of type

Java error: illegal start of expression

java: Why does the program give "illegal start of type" error?

Java 允许您简单地将语句放在 class 的正文中。您总是需要在这些语句周围包含一个 "block"。

换句话说:第一个工作示例的最简单方法是向 class 添加一个 main 方法并将代码移到其中。表示具有签名 public static void main(String[] args)

的方法

除此之外:不要 "wait" 直到出现多个错误。从一个空 class 开始。在那里输入一个新结构。救球; 运行 编译器。寻找您需要的下一个 "element"。

对于初学者,您的策略(让我们编写 10、20 行代码;然后希望它有效)根本行不通。你那样做是在浪费你(和我们)的时间。你看,这是非常基础的东西,你不应该求助于其他人来向你解释。你应该从小事做起,自己想办法解决所有这些问题。因为那才是学习编程的精髓。

class address
{
    String address;
    String newaddr = address.trim();
    final int ziplength =4;
    String input;
    Scanner in = new Scanner(System.in);
    String temp = in.next();
    String zipcode = input.substring(input.length()-ziplength);
public address() //this is the only thing I add, but it eliminate "illegal start type error"
        {
    try 
    {
        Integer.parseInt(zipcode);
        System.out.println("PO is: "+zipcode);    
    }
    catch( Exception e) 
    {
        System.err.println("Last 4 chars are not a number.");
    }
        }
}

特别感谢@Jägermeister。他给了我宝贵的暗示。

因为我是初学者,所以我在想一个更好的方法来提高我的技能。我会尝试更多。