Quick Java Question

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • faized
    New Member
    • Mar 2008
    • 1

    Quick Java Question

    Hello all, one of the conditions for my assessment is that I shouldnt't be re-using code that is similar/same as previously used in my program. I've got "re-used" code everywhere, but not sure how to make it so that its not the same line of code with one word changed. An example below :

    Code:
        void getInput()
        {
            System.out.print("Enter Australia player name: ");
            australiaPlayerName = input.next();
            System.out.print("Enter Africa player name: ");
            africaPlayerName = input.next();
        }
    How would I shorten that method so that I'm not repeating code?
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Originally posted by faized
    Hello all, one of the conditions for my assessment is that I shouldnt't be re-using code that is similar/same as previously used in my program. I've got "re-used" code everywhere, but not sure how to make it so that its not the same line of code with one word changed. An example below :

    Code:
        void getInput()
        {
            System.out.print("Enter Australia player name: ");
            australiaPlayerName = input.next();
            System.out.print("Enter Africa player name: ");
            africaPlayerName = input.next();
        }
    How would I shorten that method so that I'm not repeating code?
    Personally I would split that method in two:

    [code=java]
    String prompt(String prompt, Scanner input) {
    System.out.prin t(prompt+": ");
    return input.next();
    }
    [/code]

    now you can do this:

    [code=java]
    Scanner input= ...;
    String australianPlaye rName= prompt("Enter Australia player name", input);
    String africaPlayerNam e= prompt("Enter Africa player name", input);
    String vegetable= prompt("Type a vegetable you like", input);
    // etc. etc.
    [/code]

    So you can properly reuse the method without any dependency on players or
    whatever.

    kind regards,

    Jos

    Comment

    Working...