Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Style Query: Verbs vs. Nouns
Index -> Programming, Java -> Java Tutorials
View previous topic Printable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: Wed Nov 22, 2006 4:19 pm   Post subject: Style Query: Verbs vs. Nouns

Inspired by a recent thread in the Help forum.

You wish to repeatedly prompt the user for a number, until a valid number is retrieved.

Which of the following do you prefer?

code:
class UtilityClass {
   public static int getInt(Scanner input, String prompt) {
      int result = 0;

      while (true) {
         try {
            System.out.print(prompt + " ");
            result = input.nextInt();
            break;
         }
         catch (InputMismatchException e) {
         }
      }

      return result;
   }

   public static int getInt(Scanner input, String prompt, String errorMessage) {
      int result = 0;

      while (true) {
         try {
            System.out.print(prompt + " ");
            result = input.nextInt();
            break;
         }
         catch (InputMismatchException e) {
            System.out.println(errorMessage);
         }
      }

      return result;
   }
}


code:
class IntGetter {
   private Scanner inputScanner;
   private String promptMessage;
   private String errorMessage;
   private boolean displayPrompt;

   public IntGetter(Scanner input, String prompt) {
      this.inputScanner = input;
      this.promptMessage = prompt;
      this.errorMessage = "";
      this.displayPrompt = false;
   }

   public IntGetter(Scanner input, String prompt, String error) {
      this.inputScanner = input;
      this.promptMessage = prompt;
      this.errorMessage = error;
      this.displayPrompt = true;
   }

   public int get() {
      int result = 0;

      while (true) {
         try {
            System.out.print(promptMessage + " ");
            result = inputScanner.nextInt();
            break;
         }
         catch (InputMismatchException e) {
            if (displayPrompt) {
               System.out.println(errorMessage);
            }
         }
      }

      return result;
   }
}


The latter should probably have accessor methods, but I don't feel like writing that cruft, so imagine them. Smile
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> Programming, Java -> Java Tutorials
View previous topic Tell A FriendPrintable versionDownload TopicRate TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: