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

后端 未结 2 1476
暖寄归人
暖寄归人 2021-01-17 06:40
class address
{

String address;
String newaddr = address.trim();
final int ziplength =4;
    String input;
    Scanner in = new Scanner(System.in);
    String temp          


        
相关标签:
2条回答
  • 2021-01-17 07:25

    Java does not allow you to simply put statements in the body of a class. You always need an enclosing "block" around those statements.

    In other words: the easiest way to a first working example would be to add a main method to your class and to move your code in there. Meaning a method with signature public static void main(String[] args)

    Beside that: don't "wait" until several errors come together. Start with an empty class. Enter one new construct in there. Save; run the compiler. Go for the next "element" that you need.

    For a beginner, your strategy (lets write 10, 20 lines of code; and then lets hope it works) will not work at all. You are wasting your time (and ours) by doing it like that. You see, this is so basic stuff that you should not turn to other people to explain them to you. You should start small and figure all these things yourself. Because that is the essence of learning programming.

    0 讨论(0)
  • 2021-01-17 07:25
    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.");
        }
            }
    }
    

    Special thank you for @Jägermeister . He gives me valuable hint.

    Since I am a beginner, I am thinking a better way to improve my skills. I will try more.

    0 讨论(0)
提交回复
热议问题