How to debug “java.lang.ArrayIndexOutOfBoundsException” in a Java program?

前端 未结 1 1664
清歌不尽
清歌不尽 2021-01-25 00:08

I\'ve just started to learn Java,and I\'ve got some questions for my code. Well,the task is to get a number and print a matrix like this:

get 3,and print:
    1          


        
相关标签:
1条回答
  • 2021-01-25 01:02

    (The answer there supposes you have an IDE, like Eclipse).

    The really, really dirty way

    You can, when in doubt, always rely on a good old System.out.println(yourobject). Be careful about objects, never forget that you can turn them into String and check inner objets (in your case, visited[1][2] or matrix[2][0] for example). BUT it sucks. Really. It might suffice for your needs, but it is really a bad habit to take.

    The 'okay' way (EDIT)

    Use a tool named SLF4J to get some additional traces. As you are only on a small method and not a complete project, I would not command you to deploy this tool yet, but keep in mind that it is a good way to both figure out what happens and have your console logging what you need, especially when the projects are getting intersting (read: bigger).

    The good and elegant way

    Learn a bit about a tool called debug mode. You can find further help on the Eclipse help center, but basically the steps are:

    • Place a breakpoint. On the left of your code (with line numbers), you can right-click to toogle / enable / disable breakpoints.
    • Run your program in debug. It is a little bug (how convenient) near the classic run icon. You'll get redirected to the debug perspective.
    • The run will be interrupted where you toogled your breakpoint. There, you will be able to go, step by step, into your code. You will also be able to check the state of every variable you declared, in order to identify your problem.
    • [Your job here is to make the necessary changes]
    • Now you know about debugger, ArrayOutOfBoundsException and became a better person in general thanks to this good practice.

    Vogella has a good tutorial about how to use the debugger in a nice way. Learn to use it if you plan on keeping on Java, because this will save you a lot of time (an awful lot, believe me).

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