{"id":23065,"date":"2022-11-23T14:45:21","date_gmt":"2022-11-23T09:15:21","guid":{"rendered":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/"},"modified":"2022-11-23T14:45:21","modified_gmt":"2022-11-23T09:15:21","slug":"solved-java-error-variable-scopes-in-if-statements","status":"publish","type":"post","link":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/","title":{"rendered":"[Solved] Java: ERROR variable scopes in if statements"},"content":{"rendered":"<p> [ad_1]<br \/>\n<\/p>\n<div id=\"answer-46289095\" class=\"answer js-answer accepted-answer js-accepted-answer\" data-answerid=\"46289095\" data-parentid=\"46288877\" data-score=\"0\" data-position-on-page=\"1\" data-highest-scored=\"1\" data-question-has-accepted-highest-score=\"1\" itemprop=\"acceptedAnswer\" itemscope itemtype=\"https:\/\/schema.org\/Answer\">\n<div class=\"post-layout\">\n<div class=\"votecell post-layout--left\"><\/div>\n<div class=\"answercell post-layout--right\">\n<div class=\"s-prose js-post-body\" itemprop=\"text\">\n<p>The reason you are getting the error is that some execution paths in your code do not set a value to <code>hours<\/code>. It is difficult to see this problem because you are mixing input validation with result calculation logic.<\/p>\n<p>You could just initialize hours to 0, but I suspect that your program still won&#8217;t work the way you expect.<\/p>\n<p>While there are many ways to solve this problem, I would recommend breaking the code into a number of smaller parts to solve each problem individually. There are a number of advantages to this, including being able to test each piece separately, and making it easier to understand and, more importantly, maintain each piece.<\/p>\n<p>If you separate each piece into it&#8217;s own method, your main method could look something like this:<\/p>\n<pre><code>public static void main(String[] args) {\n    int plan = getPlanFromUser();\n    int month = getMonthFromUser();\n    int hours = getHoursFromUser(month);\n    evaluateSavings(plan, month, hours);\n}\n<\/code><\/pre>\n<p>Then to get the plan from the user, you write a method called getPlanFromUser() that retrieves the user&#8217;s input and validates it before returning a valid selection.<\/p>\n<p>Likewise with the other &#8216;get&#8217; methods, with the special case being <code>getHoursFromUser()<\/code> where you pass the month so that the method can validate that the correct hours are entered.<\/p>\n<p>Finally, your <code>evaluateSavings()<\/code> method receives all the users input (which has already been validated) and simply calculates the appropriate savings.<\/p>\n<p>Taking this kind of approach means that you only have to solve a couple of problems in each method, and you don&#8217;t have to think about everything at the same time.<\/p>\n<p><strong>EDIT: Here&#8217;s the code reorganised as described above<\/strong><\/p>\n<pre><code>import java.util.Scanner;\n\npublic class HW04P05 {\n\n    private static final int PACKAGE_1 = 1;\n    private static final int PACKAGE_2 = 2;\n    private static final int PACKAGE_3 = 3;\n\n    public static void main(String[] args) {\n        Scanner input = new Scanner(System.in);\n\n        int plan = getPlan(input);\n        int month = getMonth(input);\n        int hours = getHours(input, month);\n        calculateSavings(plan, hours);\n    }\n\n    private static int getPlan(Scanner input) {\n        \/\/ packages menu\n        System.out.println();\n        System.out.println(\"[1] Package 1: $15.95 a month for up to 10 hours of service. Additional hours are $2.00 per hour.\");\n        System.out.println(\"[2] Package 2: $20.95 a month for up to 20 hours of service. Additional hours are $1.00 per hour.\");\n        System.out.println(\"[3] Package 3: $30.99 per month unlimited access.\");\n        System.out.println();\n        System.out.print(\"Enter [1 - 3] for select your package: \");\n\n        \/\/ get input\n        int choice = input.nextInt();\n\n        \/\/ input validation\n        System.out.println(\" \");\n        if (choice &lt; 0) {\n            exitProgram(\"The menu choice cannot be negative, must be a value [1 - 3]\");\n        } else if (choice == 0) {\n            exitProgram(\"The menu choice cannot be zero, must be a value [1 - 3]\");\n        } else if (choice &gt; 3) {\n            exitProgram(\"The menu choice must be a value [1 - 3]\");\n        }\n        return choice;\n    }\n\n    private static int getMonth(Scanner input) {\n        \/\/ month menu\n        System.out.println(\"[1] January   [4] April  [7] July       [10] October\");\n        System.out.println(\"[2] February  [5] May    [8] August     [11] November\");\n        System.out.println(\"[3] March     [6] June   [9] September  [12] December\");\n        System.out.println(\"\");\n        System.out.print(\"Enter [1 - 12] for select billed month: \");\n\n        \/\/ get input\n        int month = input.nextInt();\n\n        \/\/ input validation\n        if (month &lt; 0) {\n            exitProgram(\"The month cannot be negative, must be a value [1 - 12]\");\n        } else if (month == 0) {\n            exitProgram(\"The month cannot be zero, must be a value [1 - 12]\");\n        } else if (month &gt; 12) {\n            exitProgram(\"The month must be a value [1 - 12]\");\n        }\n        return month;\n    }\n\n    private static int getHours(Scanner input, int month) {\n        \/\/ hours menu\n        System.out.println(\" \");\n        System.out.print(\"Enter the number of hours the plan package was used: \");\n\n        \/\/ get input\n        int hours = input.nextInt();\n\n        \/\/ input validation\n        if (hours &lt; 0) {\n            exitProgram(\"ERROR: The number of hours cannot be negative.\");\n        }\n        if ((month ==  1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) &amp;&amp; hours &gt; 744) {\n            exitProgram(\"ERROR: The number of hours cannot be higher than 744 on the month selected.\");\n        }\n        if ((month ==  4 || month == 6 || month == 9 || month == 11) &amp;&amp; hours &gt; 720) {\n            exitProgram(\"ERROR: The number of hours cannot be higher than 720 on the month selected.\");\n        }\n        if (month == 2 &amp;&amp; hours &gt; 672) {\n            exitProgram(\"ERROR: The number of hours cannot be higher than 672 on the month selected.\");\n        }\n\n        return hours;\n    }\n\n    private static void calculateSavings(int plan, int hours) {\n        double pricePlan1 = calculatePricePlan1(hours);\n        double pricePlan2 = calculatePricePlan2(hours);\n        double pricePlan3 = 30.99;\n\n        switch(plan) {\n            case PACKAGE_1:\n                System.out.println(String.format(\"The cost of your bill is: $%.2f\", pricePlan1));\n                if (pricePlan1 &gt; pricePlan2) {\n                    System.out.println(String.format(\"On package 2 you could have saved $%.2f\", pricePlan1 - pricePlan2));\n                }\n                if (pricePlan1 &gt; pricePlan3) {\n                    System.out.println(String.format(\"On package 3 you could have saved $%.2f\", pricePlan1 - pricePlan3));\n                }\n                break;\n\n            case PACKAGE_2:\n                System.out.println(String.format(\"The cost of your bill is: $%.2f\", pricePlan2));\n                if (pricePlan2 &gt; pricePlan3) {\n                    System.out.println(String.format(\"On package 3 you could have saved $%.2f\", pricePlan2 - pricePlan3));\n                }\n                break;\n\n            case PACKAGE_3:\n                System.out.println(String.format(\"The cost of your bill is: $%.2f\", pricePlan3));\n                break;\n        }\n    }\n\n    private static double calculatePricePlan1(int hours) {\n        if (hours &lt;= 10) {\n            return 15.95;\n        }\n\n        return 15.95 + ((hours - 10) * 2);\n    }\n\n\n    private static double calculatePricePlan2(int hours) {\n        if (hours &lt;= 20) {\n            return 20.95;\n        }\n\n        return 20.95 + (hours - 20);\n    }\n\n    private static void exitProgram(String reason) {\n        System.out.println(reason);\n        System.out.println(\"The program will now exit.\");\n        System.exit(1);\n    }\n}\n<\/code><\/pre>\n<p>Note that each method fits on one &#8216;page&#8217; and each can be understood and tested independently. This approach makes it much easier for other developers to understand what the code does (and therefore reduces maintenance cost).<\/p>\n<\/p><\/div>\n<div class=\"mt24\"><\/div>\n<\/div>\n<p>            <span class=\"d-none\" itemprop=\"commentCount\">1<\/span> <\/p><\/div>\n<\/div>\n<p>[ad_2]<\/p>\n<p>solved Java: ERROR variable scopes in if statements <\/p>\n","protected":false},"excerpt":{"rendered":"<p>[ad_1] The reason you are getting the error is that some execution paths in your code do not set a value to hours. It is difficult to see this problem because you are mixing input validation with result calculation logic. You could just initialize hours to 0, but I suspect that your program still won&#8217;t &#8230; <a title=\"[Solved] Java: ERROR variable scopes in if statements\" class=\"read-more\" href=\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\" aria-label=\"More on [Solved] Java: ERROR variable scopes in if statements\">Read more<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[320],"tags":[943,639,323,893,366],"class_list":["post-23065","post","type-post","status-publish","format-standard","hentry","category-solved","tag-compiler-errors","tag-if-statement","tag-java","tag-switch-statement","tag-variables"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>[Solved] Java: ERROR variable scopes in if statements - JassWeb<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"[Solved] Java: ERROR variable scopes in if statements - JassWeb\" \/>\n<meta property=\"og:description\" content=\"[ad_1] The reason you are getting the error is that some execution paths in your code do not set a value to hours. It is difficult to see this problem because you are mixing input validation with result calculation logic. You could just initialize hours to 0, but I suspect that your program still won&#8217;t ... Read more\" \/>\n<meta property=\"og:url\" content=\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\" \/>\n<meta property=\"og:site_name\" content=\"JassWeb\" \/>\n<meta property=\"article:published_time\" content=\"2022-11-23T09:15:21+00:00\" \/>\n<meta name=\"author\" content=\"Kirat\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Kirat\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"4 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\"},\"author\":{\"name\":\"Kirat\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\"},\"headline\":\"[Solved] Java: ERROR variable scopes in if statements\",\"datePublished\":\"2022-11-23T09:15:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\"},\"wordCount\":300,\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"keywords\":[\"compiler-errors\",\"if-statement\",\"java\",\"switch-statement\",\"variables\"],\"articleSection\":[\"Solved\"],\"inLanguage\":\"en-US\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\",\"url\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\",\"name\":\"[Solved] Java: ERROR variable scopes in if statements - JassWeb\",\"isPartOf\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#website\"},\"datePublished\":\"2022-11-23T09:15:21+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/jassweb.com\/solved\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"[Solved] Java: ERROR variable scopes in if statements\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/jassweb.com\/solved\/#website\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"name\":\"JassWeb\",\"description\":\"Build High-quality Websites\",\"publisher\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/jassweb.com\/solved\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/jassweb.com\/solved\/#organization\",\"name\":\"Jass Web\",\"url\":\"https:\/\/jassweb.com\/solved\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"contentUrl\":\"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png\",\"width\":693,\"height\":132,\"caption\":\"Jass Web\"},\"image\":{\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31\",\"name\":\"Kirat\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"contentUrl\":\"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750\",\"caption\":\"Kirat\"},\"sameAs\":[\"http:\/\/jassweb.com\"],\"url\":\"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"[Solved] Java: ERROR variable scopes in if statements - JassWeb","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/","og_locale":"en_US","og_type":"article","og_title":"[Solved] Java: ERROR variable scopes in if statements - JassWeb","og_description":"[ad_1] The reason you are getting the error is that some execution paths in your code do not set a value to hours. It is difficult to see this problem because you are mixing input validation with result calculation logic. You could just initialize hours to 0, but I suspect that your program still won&#8217;t ... Read more","og_url":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/","og_site_name":"JassWeb","article_published_time":"2022-11-23T09:15:21+00:00","author":"Kirat","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Kirat","Est. reading time":"4 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#article","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/"},"author":{"name":"Kirat","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31"},"headline":"[Solved] Java: ERROR variable scopes in if statements","datePublished":"2022-11-23T09:15:21+00:00","mainEntityOfPage":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/"},"wordCount":300,"publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"keywords":["compiler-errors","if-statement","java","switch-statement","variables"],"articleSection":["Solved"],"inLanguage":"en-US"},{"@type":"WebPage","@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/","url":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/","name":"[Solved] Java: ERROR variable scopes in if statements - JassWeb","isPartOf":{"@id":"https:\/\/jassweb.com\/solved\/#website"},"datePublished":"2022-11-23T09:15:21+00:00","breadcrumb":{"@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/jassweb.com\/solved\/solved-java-error-variable-scopes-in-if-statements\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/jassweb.com\/solved\/"},{"@type":"ListItem","position":2,"name":"[Solved] Java: ERROR variable scopes in if statements"}]},{"@type":"WebSite","@id":"https:\/\/jassweb.com\/solved\/#website","url":"https:\/\/jassweb.com\/solved\/","name":"JassWeb","description":"Build High-quality Websites","publisher":{"@id":"https:\/\/jassweb.com\/solved\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/jassweb.com\/solved\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/jassweb.com\/solved\/#organization","name":"Jass Web","url":"https:\/\/jassweb.com\/solved\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/","url":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","contentUrl":"https:\/\/jassweb.com\/wp-content\/uploads\/2021\/02\/jass-website-logo-1.png","width":693,"height":132,"caption":"Jass Web"},"image":{"@id":"https:\/\/jassweb.com\/solved\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/65c9c7b7958150c0dc8371fa35dd7c31","name":"Kirat","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/jassweb.com\/solved\/#\/schema\/person\/image\/","url":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","contentUrl":"https:\/\/jassweb.com\/solved\/wp-content\/litespeed\/avatar\/1261af3c9451399fa1336d28b98ea3bb.jpg?ver=1775798750","caption":"Kirat"},"sameAs":["http:\/\/jassweb.com"],"url":"https:\/\/jassweb.com\/solved\/author\/jaspritsinghghumangmail-com\/"}]}},"_links":{"self":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/23065","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/comments?post=23065"}],"version-history":[{"count":0,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/posts\/23065\/revisions"}],"wp:attachment":[{"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/media?parent=23065"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/categories?post=23065"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/jassweb.com\/solved\/wp-json\/wp\/v2\/tags?post=23065"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}