Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Java (https://www.askmehelpdesk.com/forumdisplay.php?f=440)
-   -   Why can't I use the string "input" in the method "ifs"? (https://www.askmehelpdesk.com/showthread.php?t=777535)

  • Dec 3, 2013, 10:43 PM
    PunchingDolphin
    Why can't I use the string "input" in the method "ifs"?
    so I was trying to tidy up the main method, and tried to move the if statements to another method but it says can't find symbol symbol: variable input location class engine.

    I'm new to coding so please respond with lots of easily understandable details. Thx

    Code:

    import java.util.Scanner;
    public class engine
    {
       
        public static void main(String[] args)
        {
            String input;
            Printer("Would you like to go Left or Right?");
            Scanner Keyboard = new Scanner(System.in);
            input = Keyboard.nextLine();
            //ifs();



        }
        public static void Printer(String a){
            System.out.println(a);
        }
        public static void ifs(){
              if(input.equals ("Left")){
                Left();
            }
            if(input.equals ("left")){
                Left();
            }
        }
        public static void Left(){
            System.out.println("working");
        }
       
       
        }

  • Dec 3, 2013, 10:46 PM
    PunchingDolphin
    I did remove the comment // and tried it again and still didn't work
  • Dec 6, 2013, 05:27 PM
    Scleros
    Moving the ifs doesn't really tidy up the main method in my opinion and only serves to move the logic for processing an input away from the actual entry of the input making the code harder to follow for subsequent maintenance.

    The input declared in main() is not in scope in ifs(). Either 1) pass input to ifs(), 2) move the ifs() logic back to main, or 3) declare input as a field. I suggest #2.

    Ifs() is also public for the class. That's untidy in the sense that if this is an engine class (or any) it probably shouldn't be exposing methods only useful internally to the class and unable to be used by external code.

    More info:
    The Java™ Tutorials: Declaring Member Variables
    Incremental Java: Local Variables and Scope

  • All times are GMT -7. The time now is 09:45 AM.