当我创建一个类时,我在“try-catch”块中收到“非法启动类型”错误

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."); } } 

此代码段从字符串中提取最后四个字符,并查看它们是否为邮政编码。

我评论了NetBeans中报告“非法启动类型错误”的要点。

我想知道,如果我在创建一个类时不能使用try-catch? 或者,这堂课会错过什么?

我试着搜索stackoverflow。 但我仍然感到困惑。 这是一些链接。

Java非法启动类型

Java错误:非法启动表达式

java:为什么程序会出现“非法启动类型”错误?

Java不允许您简单地将语句放在类的主体中。 你总是需要围绕这些陈述附上一个封闭的“块”。

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

除此之外:不要“等待”,直到几个错误汇集在一起​​。 从一个空课开始。 在那里输入一个新构造。 保存; 运行编译器。 去寻找你需要的下一个“元素”。

对于初学者,你的策略(让我们编写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。 他给了我宝贵的暗示。

由于我是初学者,我正在考虑提高自己技能的更好方法。 我会尝试更多。