Results 1 to 16 of 16
  1. - Top - End - #1
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default I'm learning Java accelerated and I need help

    So, I signed up for a program where I will have 10 weeks of learning about different program languages and applications for programming. A week and a half has gone by and I've made some progress on the project I've been working on, but I've encountered some snags here and there. It's been about 3 years since I really coded and I haven't programmed in Java before. Since it's only been a week, I keep forgetting certain syntax I need to organize my code and I forget what I'm trying to do is called sometimes. I know what I want to do for my code, but it's been slow trying to figure out the 'how' to word it. So I was wondering if anyone experienced in Java and SQL be willing to help me out with a few sections of my code whenever I get stuck? I'll post examples of my code as I think if I have a working reference of different methods and how the code would go together, I'd be able to work out most of it myself.

    The first bit is this bit of code I have. I made a switch statement inside a do/while loop. Essentially I have 3 cases and I have the user inputs either a number '1', '2', or '3'. If they decide not to make any of those selections, there will be an outputted "You goofed up!" message (not worded exactly that way) and the while loop will send the user back to the top of the do loop. Now, what I'm trying to do is for each case listed that it would take the user to another part of the code, I think the terminology is "calling a method?" I'm not quite sure how to do this and the online examples I've looked at didn't clear up my confusion much. Here's a simplified version of my code:
    Code:
    do {
    
    Switch ...
          Case 1:
    
          //Would send user to another section of code, like CustomerLogin() or some other class.
    
          Case 2:
    ...
          Case 3:
    ...
          Default:
          system.out.println("You goofed!")
    } while (default condition is reached)
    The bolded commented bit of the code is what I'm trying to do. Everything else in this switch statement is much more streamlined. Imagine there is a CustomerLogin() class somewhere else in the code and I'm trying to send the user there.

    Any help given would be greatly appreciated.

  2. - Top - End - #2
    Ogre in the Playground
     
    Telok's Avatar

    Join Date
    Mar 2005
    Location
    PRAK

    Default Re: I'm learning Java accelerated and I need help

    Depending on how complicated the current function and class are thete are three basic solutions.

    1 Make three new functions in the current class, call them, pass in your parameters.

    2 Make a new class with the functions you want to call. Instanciate it before the loop and call it's functions.

    3 Make three new classes with the functions you need. Make new instances and call functions within the loop.

    If your project is small enough to fit decently in a single file you probably want #1. If the functions from the loop are related or will be calling each other then probably #2. If the three branches of code are divergent or reasonably large then #3.

    For larger, significantly more complicated projects, you could turn to making a listener system or something. But these sorts of projects don't normally get big enough to make that time efficent.

    I'm probably not as complete or clear as I could be. Sorry. Morning, first cuppa and doing this mobile. Could probably help more later.
    Niven's Laws, #5
    If you've nothing to say, say it any way you like. Stylistic innovations, contorted story lines or none, exotic or genderless pronouns, internal inconsistencies, the recipe for preparing your lover as a cannibal banquet: feel free. If what you have to say is important and/or difficult to follow, use the simplest language possible. If the reader doesn't get it then, let it not be your fault.

  3. - Top - End - #3
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Telok View Post
    Depending on how complicated the current function and class are thete are three basic solutions.

    1 Make three new functions in the current class, call them, pass in your parameters.

    2 Make a new class with the functions you want to call. Instanciate it before the loop and call it's functions.

    3 Make three new classes with the functions you need. Make new instances and call functions within the loop.

    If your project is small enough to fit decently in a single file you probably want #1. If the functions from the loop are related or will be calling each other then probably #2. If the three branches of code are divergent or reasonably large then #3.

    For larger, significantly more complicated projects, you could turn to making a listener system or something. But these sorts of projects don't normally get big enough to make that time efficent.

    I'm probably not as complete or clear as I could be. Sorry. Morning, first cuppa and doing this mobile. Could probably help more later.
    I have multiple packages. The project involves having this Java program merge with SQL and have the user register an account with the user putting in their own username and password (and then later be able to log in). I'm trying to give the user the option to say, "I need to make an account" or "I have an account and want to login" in which the switch statement would send them to the proper class or method that would then allow them to proceed through the application. I'm just drawing a blank on the specific phrasing of the code to send the user to these locations from out of the switch statement (in other words, out of the do/while loop).

  4. - Top - End - #4
    Dwarf in the Playground
    Join Date
    Jun 2014

    Default Re: I'm learning Java accelerated and I need help

    Is your issue calling a method from somewhere else?
    Or, after you call the code from somewhere else, you end up back inside the looping switch statement?
    Last edited by sleepy hedgehog; 2019-04-25 at 11:27 AM.

  5. - Top - End - #5
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by sleepy hedgehog View Post
    Is your issue calling a method from somewhere else?
    Or, after you call the code from somewhere else, you end up back inside the looping switch statement?
    Both. I want to call a method where the user is sent to that method of the code, and make sure that the user doesn't end up back in the loop after a valid case has been selected.

  6. - Top - End - #6
    Barbarian in the Playground
     
    PaladinGuy

    Join Date
    Sep 2016

    Post Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Silverraptor View Post
    Both. I want to call a method where the user is sent to that method of the code, and make sure that the user doesn't end up back in the loop after a valid case has been selected.
    Regarding the exiting

    Code:
    Return abc();
    Potentially works, particularly good if you actually want to return the result of abc().
    Not so good if you want to call abc() or def() which return different things.

    Failing that it's going to come 'back to that code' at some point. but
    Code:
    abc();
    break;
    should work and immediately break out the loop, but it can get messy.

    Similarly
    Code:
    canExit=false;
    while(!canExit){
      if(condition){
        abc();
        boolean canExit()=true;
      }
    }
    should work but can be ugly.

    Finally rather than having a loop you could have the function call the starting point again in the case of invalid input (provided the language does tail-recursion).

    Regarding the called function. In Java the function has to be in a class somewhere... (for which Telok gives 3 suggestions. You could also have static functions).


    FWIW I'm hoping to do something similar in Python (not for banking though). With a structure something like the following...
    Code:
    class rootMenu extends Menu{
       start(){
           Menu current=this;
           while(...){
               current.display();
               current=current.nextMenu(getChoice())
           }
       }
       String displayMenu(){
       }
       Menu nextMenu(choice){
          switch choice{
                  ...
         }
          return this;
       }
    }

  7. - Top - End - #7
    Dwarf in the Playground
    Join Date
    Jun 2014

    Default Re: I'm learning Java accelerated and I need help

    OK. First, lets look at how to call methods.
    Lets say elsewhere, you have a class for dealing with logging people in.
    Code:
    public class Login {
        public Login() {}
        public boolean customerLogin(String loginID) {
            System.out.println("Successfully logging in customer " + loginID);
            return True;
        }
    }
    First, you need to create an instance of an object, by using the objects constructor.
    Then from that instance, you can call the functions that that object has.
    Also, you will probably need to import it into your current file. I'm hoping you can do this, because it depends on your project's setup.

    Code:
    import Login 
    ...
    ...
    ...
    Case 1:
        Login loginInfo = new Login();
        loginInfo.customerLogin("John Smith");
        break;
    }
    Now, it's successfully calling our code, but it's stuck in an infinite loop of:
    "Successfully logging in customer John Smith"
    "Successfully logging in customer John Smith"
    "Successfully logging in customer John Smith"
    ...

    To deal with this, we'll add a boolean for breaking the loop, lets call it repeat.
    When it's true, that means the code needs to repeat, and when it's false, we can stop looping.
    Code:
    boolean repeat = False;
    do {
    
    Switch ...
          Case 1:
    
          //Would send user to another section of code, like CustomerLogin() or some other class.
    
          Case 2:
          repeat = False;
    ...
          Case 3:
          repeat = False;
    ...
          Default:
          system.out.println("You goofed!")
          repeat = True;
          break;
    } while (repeat is true and default condition is reached)
    Some various notes:
    • An object will only last until the curly brace that it's created in ends, unless it's saved elsewhere.
    • If you really don't want to create an instance of a class, you can use "static", and then say Login.customerLogin("Blah");
      But don't worry about that for now.
    Last edited by sleepy hedgehog; 2019-04-25 at 01:17 PM.

  8. - Top - End - #8
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by sleepy hedgehog View Post
    OK. First, lets look at how to call methods.
    Lets say elsewhere, you have a class for dealing with logging people in.
    Code:
    public class Login {
        public Login() {}
        public boolean customerLogin(String loginID) {
            System.out.println("Successfully logging in customer " + loginID);
            return True;
        }
    }
    First, you need to create an instance of an object, by using the objects constructor.
    Then from that instance, you can call the functions that that object has.
    Also, you will probably need to import it into your current file. I'm hoping you can do this, because it depends on your project's setup.

    Code:
    import Login 
    ...
    ...
    ...
    Case 1:
        Login loginInfo = new Login();
        loginInfo.customerLogin("John Smith");
        break;
    }
    Now, it's successfully calling our code, but it's stuck in an infinite loop of:
    "Successfully logging in customer John Smith"
    "Successfully logging in customer John Smith"
    "Successfully logging in customer John Smith"
    ...

    To deal with this, we'll add a boolean for breaking the loop, lets call it repeat.
    When it's true, that means the code needs to repeat, and when it's false, we can stop looping.
    Code:
    boolean repeat = False;
    do {
    
    Switch ...
          Case 1:
    
          //Would send user to another section of code, like CustomerLogin() or some other class.
    
          Case 2:
          repeat = False;
    ...
          Case 3:
          repeat = False;
    ...
          Default:
          system.out.println("You goofed!")
          repeat = True;
          break;
    } while (repeat is true and default condition is reached)
    Some various notes:
    • An object will only last until the curly brace that it's created in ends, unless it's saved elsewhere.
    • If you really don't want to create an instance of a class, you can use "static", and then say Login.customerLogin("Blah");
      But don't worry about that for now.
    I was looking into doing this, but someone told me that if I made the boolean status within the switch statement, it would not translate over to the while part of the loop with the 'true' status. If the case is that it does then I can definitely change the design of the case statements.

  9. - Top - End - #9
    Barbarian in the Playground
     
    PaladinGuy

    Join Date
    Sep 2016

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Silverraptor View Post
    I was looking into doing this, but someone told me that if I made the boolean status within the switch statement, it would not translate over to the while part of the loop with the 'true' status. If the case is that it does then I can definitely change the design of the case statements.
    If (as shown and noted) it's declared before the loop it will be existing for the whole loop and until the next } braces (for good and ill).
    If it's declared in the loop then it becomes a bit complex (I think it might still work if you test at the end like that).
    If you took the switch to be a function in it's own right, then you will have problems
    Spoiler: pseudocode
    Show

    Code:
      public main(){
        ...
        boolean repeat=true;
        while(repeat){
            this.switchFn();
        }
      }
      private void switchFn(boolean repeat){
          Switch...
          ...
            repeat=false;
      }
    Would loop for ever (if you fixed it to compile)

  10. - Top - End - #10
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by jayem View Post
    If (as shown and noted) it's declared before the loop it will be existing for the whole loop and until the next } braces (for good and ill).
    If it's declared in the loop then it becomes a bit complex (I think it might still work if you test at the end like that).
    If you took the switch to be a function in it's own right, then you will have problems
    Spoiler: pseudocode
    Show

    Code:
      public main(){
        ...
        boolean repeat=true;
        while(repeat){
            this.switchFn();
        }
      }
      private void switchFn(boolean repeat){
          Switch...
          ...
            repeat=false;
      }
    Would loop for ever (if you fixed it to compile)
    This is similar to how I did it. I put a Boolean value as True outside the do/while loop and if none of the cases in the Switch statement are satisfied, then the true value would hit the while part of the loop and go back to the top of the do loop.


    Edit: Nevermind! I just realized why I was doing this wrong. I was thinking about this from a C++/Machine Assembly way. I was trying to move through the code, into and out of loops. But now I realize, I don't want to move out of the loop. I just have that case call a method, which would then call another method and so on and so forth, while not actually leaving the loop! And then I can have the last method I'm calling have the exit or close out command which would shut down the application then! Is this correct? If so, then my mind would be blow by this revelation!
    Last edited by Silverraptor; 2019-04-25 at 04:30 PM.

  11. - Top - End - #11
    Surgebinder in the Playground Moderator
     
    Douglas's Avatar

    Join Date
    Aug 2005
    Location
    Mountain View, CA
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Silverraptor View Post
    Edit: Nevermind! I just realized why I was doing this wrong. I was thinking about this from a C++/Machine Assembly way. I was trying to move through the code, into and out of loops. But now I realize, I don't want to move out of the loop. I just have that case call a method, which would then call another method and so on and so forth, while not actually leaving the loop! And then I can have the last method I'm calling have the exit or close out command which would shut down the application then! Is this correct? If so, then my mind would be blow by this revelation!
    Technically, yes you can do it that way, but in almost all cases it's an utterly horrible hack and should be avoided by changing your program's design. System.exit() is for when things have gone absolutely unrecoverably wrong and the program needs to shut down to get out of whatever bad state it's in, not for the normal and routine end of program execution.

    I get the feeling that your actual main issue is poor conceptual design of how the program is supposed to work in general, and there's a lot of missing context that we'd need to be able to advise you on that.
    Like 4X (aka Civilization-like) gaming? Know programming? Interested in game development? Take a look.

    Avatar by Ceika.

    Archives:
    Spoiler
    Show
    Saberhagen's Twelve Swords, some homebrew artifacts for 3.5 (please comment)
    Isstinen Tonche for ECL 74 playtesting.
    Team Solars: Powergaming beyond your wildest imagining, without infinite loops or epic. Yes, the DM asked for it.
    Arcane Swordsage: Making it actually work (homebrew)

  12. - Top - End - #12
    Titan in the Playground
     
    Silverraptor's Avatar

    Join Date
    Feb 2009
    Location
    A nice, sparkly place.
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Just talked with another person and he explained to me that I didn't even need the loop. I just set the default at the end of the switch statement to call the method of the Switch statement, which would give the user the choice again (since they obviously didn't select one to begin with).

  13. - Top - End - #13
    Titan in the Playground
     
    BlackDragon

    Join Date
    Feb 2007
    Location
    Manchester, UK
    Gender
    Male

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Silverraptor View Post
    Just talked with another person and he explained to me that I didn't even need the loop. I just set the default at the end of the switch statement to call the method of the Switch statement, which would give the user the choice again (since they obviously didn't select one to begin with).
    I'm not particularly familiar with Java, but that sounds like a very dodgy "optimisation" to me--calling a method has an overhead you don't want to be incurring unless you have to. In this case, I would expect the program to eventually crash due to running out of stack space if they keep selecting an invalid option, although I have no idea how long that would take.

  14. - Top - End - #14
    Barbarian in the Playground
     
    PaladinGuy

    Join Date
    Sep 2016

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by Silverraptor View Post
    Just talked with another person and he explained to me that I didn't even need the loop. I just set the default at the end of the switch statement to call the method of the Switch statement, which would give the user the choice again (since they obviously didn't select one to begin with).
    Both of these have the potential to cause stack issues, although both will work for small chains/mistakes.
    In Functional languages often it would be the good way to do it (if you return a function call, it 'returns' before calling the function).
    Java is Object Orientated and doesn't do this by itself.
    In both cases you really want a question to flow out and a response [void being acceptable, and being roughly equiv to I'm done] to flow back. However once you know that response you can return back (if you can't because you need to do something else at the end the program might be restructurable or you can fudge it).

    To contradict Factorum slightly, I would say with Java more function calls potentially could speed it up (it gives the JIT aspects more to play with, and it could always inline it). But you do want them to be nice ones.
    Last edited by jayem; 2019-04-26 at 01:56 AM.

  15. - Top - End - #15
    Dwarf in the Playground
    Join Date
    Jun 2014

    Default Re: I'm learning Java accelerated and I need help

    Quote Originally Posted by factotum View Post
    I'm not particularly familiar with Java, but that sounds like a very dodgy "optimisation" to me--calling a method has an overhead you don't want to be incurring unless you have to. In this case, I would expect the program to eventually crash due to running out of stack space if they keep selecting an invalid option, although I have no idea how long that would take.
    In a language like Python, where methods are objects, it's a valid choice.
    In Java, it's less so.
    (Technically, since Java 8, methods can be first class objects. But it's still outside Java's usual paradigm.)

  16. - Top - End - #16
    Ogre in the Playground
     
    Telok's Avatar

    Join Date
    Mar 2005
    Location
    PRAK

    Default Re: I'm learning Java accelerated and I need help

    One possibility is to put the date entry and input validation into a loop but the result is passed back out of the loop where you'll start dealing with the results. Basically only use the loop to get and clean the input and then deal with it after the loop.
    Niven's Laws, #5
    If you've nothing to say, say it any way you like. Stylistic innovations, contorted story lines or none, exotic or genderless pronouns, internal inconsistencies, the recipe for preparing your lover as a cannibal banquet: feel free. If what you have to say is important and/or difficult to follow, use the simplest language possible. If the reader doesn't get it then, let it not be your fault.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •