{"id":432,"date":"2018-04-11T18:12:29","date_gmt":"2018-04-11T18:12:29","guid":{"rendered":"http:\/\/loop.cs.mtu.edu\/?p=432"},"modified":"2023-11-06T17:27:37","modified_gmt":"2023-11-06T17:27:37","slug":"debugging-for-beginners","status":"publish","type":"post","link":"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/04\/11\/debugging-for-beginners\/","title":{"rendered":"Debugging for Beginners"},"content":{"rendered":"<p><span style=\"font-weight: 400;\">Ugh! \u00a0Bugs. They\u2019re always crawling around and flying in your face when you least expect. \u00a0The same applied to computer science bugs. They\u2019ve been around since 1947 with the early computers, and continue to annoy us today. The first recorded case of a bug was a moth that Grace Hopper found jamming a relay switch in September 1947 (<\/span><span style=\"color: #000080;\"><a style=\"color: #000080;\" href=\"http:\/\/www.computerhistory.org\/tdih\/september\/9\/\"><span style=\"font-weight: 400;\">http:\/\/www.computerhistory.org\/tdih\/september\/9\/<\/span><\/a><\/span><span style=\"font-weight: 400;\">). While not much could be done about moths flying into relay switches except climbing in and pulling them out, today we can debug without having to leave our chairs.<\/span><\/p>\n<p><!--more--><\/p>\n<p><span style=\"font-weight: 400;\">So, let\u2019s get started.<\/span><\/p>\n<h2><strong>An Ounce of Prevention<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">The best way to avoid bugs is taking steps to ensure they don\u2019t occur in the first place. \u00a0Most of these are common sense like sensibly naming variables, maintaining consistent indentation and bracketing style, determining loop conditions before programming a loop, and remembering that arrays index at 0. \u00a0Commenting a tricky bit of code can also help when you come back to it later.<\/span><\/p>\n<p><span style=\"font-weight: 400;\">First, let\u2019s look at some code that could use a bit of prevention:<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">public class BadCode {\r\n\r\n  public static void main(String[] args) {\r\n    \/\/ TODO Auto-generated method stub\r\n    \/* prints out the squares of integers from 1 to 20 inclusive\r\n     * \r\n     *\/for(int i = 0; i &lt; 20; i--) {\r\n    System.out.print(\"%4d\", Math.pow(i, i)))\r\n     \t\t\t}\r\n     \/\/ make an array and fill it with the sqrts of non-negative numbers through 20 exclusive\r\n     int [] sqrts = {};\r\n     for (int j = 1; j &lt;= 20; j++) {\r\n       sqrts[j] = Math.sqrt(j)\r\n}\r\n     \/\/ print out the array\r\n     for (int i = 0; i &gt; 20; i++);\r\n       System.out.println(sqrts[]);\r\n     \t} };\t \r\n    }\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">This code is clearly messed up:\u00a0 the closing curly brackets don\u2019t align, there are semi-colons in the wrong places and missing from the right ones, etc. \u00a0At this point it won\u2019t compile. It also has some logic errors. Try debugging it yourself, then click below to see our fixed-up version. (Hint: there are # bugs).<\/span><\/p>\n<h2><strong>A Pound of Cure<\/strong><\/h2>\n<p><span style=\"font-weight: 400;\">Sometimes we let our code get messy. \u00a0It\u2019s just part of the process of programming. \u00a0In that case, we need ways to fix it when things go wrong. \u00a0The old foolproof way of programming is scattering print statements like salt. \u00a0We\u2019ll look at doing this first. Then we\u2019ll explore a couple of other tactics.<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Scanner;\r\n\r\npublic class PrintSaltScatter {\r\n\r\n  public static void main (String [] args) {\r\n    \/\/ Read in a list of points and store them in an array.\r\n    \/\/ The first number read in will be the count\r\n    \r\n    Scanner in = new Scanner(System.in);\r\n    int count = in.nextInt();\r\n    int [] array = new int[count];\r\n    for (int i = 0; i &lt; count; i++) { \r\n      array[i] = in.nextInt();\r\n    } \r\n    \r\n    \/\/ print out the array\r\n    for (int i = 1; i &lt; count- 1; i++) {\r\n      System.out.print(array[i] + \", \");\r\n    }\r\n    \r\n    \/\/ print out the array with each element divided by 2\r\n    for (int i = 0; i &lt; count; i++) {\r\n      int j = array[i\/2];\r\n      System.out.print(j+ \", \");\r\n    }\r\n  }\r\n}<\/pre>\n<p><span style=\"font-weight: 400;\">Right now, the code compiles and runs, but it hangs at first waiting for user input.\u00a0 It&#8217;s output\u00a0 also looks a bit wonky:<\/span><\/p>\n<pre>5\r\n1\r\n2\r\n3\r\n4\r\n5\r\n2, 3, 4, 1, 1, 2, 2, 3,<\/pre>\n<p><span style=\"font-weight: 400;\">To make it easier to understand what&#8217;s happening during the development process, we should make it more clear what we want.\u00a0 We can do this by adding lines that say &#8220;Please enter how many integers you will input:&#8221; before we read in count,\u00a0 and &#8220;Please enter an integer: &#8221; before we read in each number.\u00a0 Now the code looks like this<\/span><\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Scanner;\r\n\r\npublic class PrintSaltScatter {\r\n\r\n  public static void main (String [] args) {\r\n    \/\/ Read in a list of points and store them in an array.\r\n    \/\/ The first number read in will be the count\r\n    \r\n    Scanner in = new Scanner(System.in);\r\n    System.out.println(\"Please enter how many integers you will input: \");\r\n    int count = in.nextInt();\r\n    int [] array = new int[count];\r\n    for (int i = 0; i &lt; count; i++) { \r\n      System.out.println(\"Enter an integer: \");\r\n      array[i] = in.nextInt();\r\n    } \r\n    \r\n    \/\/ print out the array\r\n    for (int i = 1; i &lt; count- 1; i++) {\r\n      System.out.print(array[i] + \", \");\r\n    }\r\n    \r\n    \/\/ print out the array with each element divided by 2\r\n    for (int i = 0; i &lt; count; i++) {\r\n      int j = array[i\/2];\r\n      System.out.print(j+ \", \");\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p>and the output looks like this:<\/p>\n<pre>Please enter how many integers you will input: \r\n5\r\nEnter an integer: \r\n1\r\nEnter an integer: \r\n2\r\nEnter an integer: \r\n3\r\nEnter an integer: \r\n4\r\nEnter an integer: \r\n5\r\n2, 3, 4, 1, 1, 2, 2, 3,<\/pre>\n<p>We can now see we entered 5 integers and that the printout is doing something weird because we&#8217;re getting only eight numbers when we should get 10.<\/p>\n<p>Let&#8217;s add a print statement to line 21 to see what&#8217;s happening:<\/p>\n<pre>System.out.println(\"i: \" + i);<\/pre>\n<p>Now it&#8217;s printing out the index after what is stored in the index.<\/p>\n<pre>Enter an integer: \r\n5\r\n2, i: 1\r\n3, i: 2\r\n4, i: 3\r\n1, 1, 2, 2, 3,<\/pre>\n<p>Aha!\u00a0 We&#8217;re indexing from 1 to 3.\u00a0 Now we&#8217;re also seeing things print on a new line.\u00a0 Let&#8217;s add another 2 statements to determine if the issue is the second or third loop.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Scanner;\r\n\r\npublic class PrintSaltScatter {\r\n\r\n  public static void main (String [] args) {\r\n    \/\/ Read in a list of points and store them in an array.\r\n    \/\/ The first number read in will be the count\r\n    \r\n    Scanner in = new Scanner(System.in);\r\n    System.out.println(\"Please enter how many integers you will input: \");\r\n    int count = in.nextInt();\r\n    int [] array = new int[count];\r\n    for (int i = 0; i &lt; count; i++) { \r\n      System.out.println(\"Enter an integer: \");\r\n      array[i] = in.nextInt();\r\n    } \r\n    \r\n    \/\/ print out the array\r\n    System.out.println(\"You entered: \");\r\n    for (int i = 1; i &lt; count- 1; i++) {\r\n      System.out.print(array[i] + \", \");\r\n      System.out.println(\"i: \" + i);\r\n    }\r\n    \r\n    \/\/ print out the array with each element divided by 2\r\n    System.out.println(\"Here are the numbers, each divided by 2: \");\r\n    for (int i = 0; i &lt; count; i++) {\r\n      int j = array[i\/2];\r\n      System.out.print(j+ \", \");\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p>Output:<\/p>\n<pre>Enter an integer: \r\n5\r\nYou entered: \r\n2, i: 1\r\n3, i: 2\r\n4, i: 3\r\nHere are the numbers, each divided by 2: \r\n1, 1, 2, 2, 3,<\/pre>\n<p>We can see two problems here now quite clearly:\u00a0 the second loop only visits indices 1, 2, and 3, and the last loop is not in fact dividing things by two.\u00a0 We fix the counter variable and condition in the second loop.\u00a0 Then we change array[i\/2] to array[i] \/ 2.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Scanner;\r\n\r\npublic class PrintSaltScatter {\r\n\r\n  public static void main (String [] args) {\r\n    \/\/ Read in a list of points and store them in an array.\r\n    \/\/ The first number read in will be the count\r\n    \r\n    Scanner in = new Scanner(System.in);\r\n    System.out.println(\"Please enter how many integers you will input: \");\r\n    int count = in.nextInt();\r\n    int [] array = new int[count];\r\n    for (int i = 0; i &lt; count; i++) { \r\n      System.out.println(\"Enter an integer: \");\r\n      array[i] = in.nextInt();\r\n    } \r\n    \r\n    \/\/ print out the array\r\n    System.out.println(\"You entered: \");\r\n    for (int i = 0; i &lt; count; i++) {\r\n      System.out.print(array[i] + \", \");\r\n      System.out.println(\"i: \" + i);\r\n    }\r\n    \r\n    \/\/ print out the array with each element divided by 2\r\n    System.out.println(\"Here are the numbers, each divided by 2: \");\r\n    for (int i = 0; i &lt; count; i++) {\r\n      int j = array[i] \/ 2;\r\n      System.out.print(j+ \", \");\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p>It still isn&#8217;t giving us quite what we want, although the second loop is now working:<\/p>\n<pre>Enter an integer: \r\n5\r\nYou entered: \r\n1, i: 0\r\n2, i: 1\r\n3, i: 2\r\n4, i: 3\r\n5, i: 4\r\nHere are the numbers, each divided by 2: \r\n0, 1, 1, 2, 2,<\/pre>\n<p>Our final problem is <a href=\"http:\/\/loop.cs.mtu.edu\/index.php\/2018\/02\/28\/integer-division\/\"> <span style=\"color: blue;\">\u200eInteger Division<\/span><\/a>, which means we need to change j to a double and either cast 2 to a double or write it as 2.0.\u00a0 With this changed, things now work as expected, and the program has been debugged.<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"null\">import java.util.Scanner;\r\n\r\npublic class PrintSaltScatter {\r\n\r\n  public static void main (String [] args) {\r\n    \/\/ Read in a list of points and store them in an array.\r\n    \/\/ The first number read in will be the count\r\n    \r\n    Scanner in = new Scanner(System.in);\r\n    System.out.println(\"Please enter how many integers you will input: \");\r\n    int count = in.nextInt();\r\n    int [] array = new int[count];\r\n    for (int i = 0; i &lt; count; i++) { \r\n      System.out.println(\"Enter an integer: \");\r\n      array[i] = in.nextInt();\r\n    } \r\n    \r\n    \/\/ print out the array\r\n    System.out.println(\"You entered: \");\r\n    for (int i = 0; i &lt; count; i++) {\r\n      System.out.print(array[i] + \", \");\r\n      System.out.println(\"i: \" + i);\r\n    }\r\n    \r\n    \/\/ print out the array with each element divided by 2\r\n    System.out.println(\"Here are the numbers, each divided by 2: \");\r\n    for (int i = 0; i &lt; count; i++) {\r\n      double j = array[i] \/ (double) 2;\r\n      System.out.print(j+ \", \");\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<p>The output is below:<\/p>\n<pre>Please enter how many integers you will input: \r\n5\r\nEnter an integer: \r\n1\r\nEnter an integer: \r\n2\r\nEnter an integer: \r\n3\r\nEnter an integer: \r\n4\r\nEnter an integer: \r\n5\r\nYou entered: \r\n1, i: 0\r\n2, i: 1\r\n3, i: 2\r\n4, i: 3\r\n5, i: 4\r\nHere are the numbers, each divided by 2: \r\n0.5, 1.0, 1.5, 2.0, 2.5,\r\n\r\n<\/pre>\n<p>Here&#8217;s the original <a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/04\/BadCode.txt\"><span style=\"color: blue;\"><span style=\"color: #008000;\">BadCode<\/span><\/span><\/a> and the final <a href=\"http:\/\/loop.cs.mtu.edu\/wp-content\/uploads\/2018\/04\/Debugged.txt\"><span style=\"color: blue;\"><span style=\"color: #008000;\">Debugged<\/span><\/span><\/a>\u00a0version so you can try out debugging on your own.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Ugh! \u00a0Bugs. They\u2019re always crawling around and flying in your face when you least expect. \u00a0The same applied to computer science bugs. They\u2019ve been around since 1947 with the early computers, and continue to annoy us today. The first recorded case of a bug was a moth that Grace Hopper found jamming a relay switch &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/loop.cs.mtu.edu\/index.php\/2018\/04\/11\/debugging-for-beginners\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;Debugging for Beginners&#8221;<\/span><\/a><\/p>\n","protected":false},"author":4,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[31],"tags":[],"class_list":["post-432","post","type-post","status-publish","format-standard","hentry","category-java"],"_links":{"self":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/432","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/users\/4"}],"replies":[{"embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/comments?post=432"}],"version-history":[{"count":15,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/432\/revisions"}],"predecessor-version":[{"id":517,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/posts\/432\/revisions\/517"}],"wp:attachment":[{"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/media?parent=432"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/categories?post=432"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/loop.cs.mtu.edu\/index.php\/wp-json\/wp\/v2\/tags?post=432"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}