need to break out a function to a method in shopping list program

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 1348 Views - Last Post: 19 November 2011 - 04:07 AM Rate Topic: -----

#1 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

need to break out a function to a method in shopping list program

Posted 17 November 2011 - 03:20 PM

Ok, i am having 2 issues with this program. Everything works as is, except that i need to break out the part of adding items to a list into the method i have created. I have tried several ways, but cant get it to work right with rest of the program. Also currently how it is, if i clear my list with -e, i am getting the -e as a value in my empty list. it is populated into the first spot of my array. I am hoping to not change much of my code, i feel like i am missing something simple.

My code is as follows

public class MyShoppingList1 {
  private static String[] shoppingList;
  public static int count;
  private java.util.Scanner scan;
  
  // constructor for the program
  private MyShoppingList1(){
    shoppingList = new String[10];
    scan = new java.util.Scanner(System.in);
    count = 0;
    System.out.println("Welcome to my Awesome Shopping List Program.");
    menu();
    command(); 
    
  }
  // This is the menu method that will print the list of commands
  public static void menu() {
    
    System.out.println("Here are the list of commands:");
    System.out.println("  -p : Print the List");
    System.out.println("  -e : Empty the List");
    System.out.println("  -x : Exit ");
    System.out.println("  -h : Print the Command List");
    
    
  }
  // this is the command function, depending on the answer will depend on what this function will do
  // thi function will call other functions as needed, or continue to add to list. 
  public void command(){
    String answer;
    System.out.print("Enter your item or command: ");
    answer = scan.next();
    while( ! answer.equals("-x")) {
      if( answer.equals("-p")){
        printList();
      }
         if(answer.equals("-e")){
           emptyList();
     
         }
            if(answer.equals("-h")) {
              menu();
            }
               // this needs to belong in the addToList method.
               System.out.print("Enter your item or command: ");
               shoppingList[count] =answer;
               count++;
               answer=scan.next();
               }
}
  // this is the add to list method that needs to be updated from the above
  public void addToList() {
  }
    
  
  // this is the method that will empty the list 
  // Although currently it will add the -e as value in the list. 
  public static void emptyList() {
    for(int i=0; i<=count; i++){
      shoppingList[i]=null;
    }
    count = 0;
    System.out.println("You just emptied your list");
   }
  
          
    
    // this is the method to print the list
    public static void printList(){
      for(int i=0; i<count;i++) {
        System.out.println((i+1) + " " + shoppingList[i]);
      }
    }
    
    // main method that will call the constructor and start program
    public static void main(String[] args) {
      new MyShoppingList1();
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: need to break out a function to a method in shopping list program

#2 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 03:38 PM

Why don't you add a new menu item for adding an item to the list, finish writing the new method, addToList(), and see what happens? It won't quite be as simple as cutting and pasting, but that's the first step.

As for your current emptyList() problem, that should go away when you clean up the handling of user commands and complete the addToList() method.

Post your updated code when you've gotten that done and are ready for more help.
Was This Post Helpful? 1
  • +
  • -

#3 blackcompe   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1159
  • View blog
  • Posts: 2,547
  • Joined: 05-May 05

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 03:42 PM

When I ran your program and entered an item, the program skipped over my chance to enter another.

Enter your item or command: Pork chops
Enter your item or command: Enter your item or command: Bananna Pudding
Enter your item or command: Enter your item or command: 



The reason being that your using Scanner.next instead of Scanner.nextLine. Scanner.next will parse all text until the first white space, but you want all text on a line.

Edit: Disregard my last statement on emptying the list.

You should really use a do/while loop and just re-design the whole loop.

DO
	PRINT PROMPT
        answer = GET INPUT
	SWITCH answer
             CASE -e: EMPTYLIST() THEN BREAK
             .
             .
             .
             CASE DEFAULT: ADDTOLIST()
        END SWITCH
WHILE answer DOES NOT EQUAL -x


This post has been edited by blackcompe: 17 November 2011 - 03:55 PM

Was This Post Helpful? 1
  • +
  • -

#4 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 04:04 PM

Greg and BlackCompe thank you so much for your help with this. I have implemented both of your suggestions. I am still having an issue with the menu selections after i cleared my list being added to my list, such as -e or -p. here is my updated code.

public class MyShoppingList1 {
  private static String[] shoppingList;
  public static int count;
  private java.util.Scanner scan;
  
  // constructor for the program
  private MyShoppingList1(){
    shoppingList = new String[10];
    scan = new java.util.Scanner(System.in);
    count = 0;
    System.out.println("Welcome to my Awesome Shopping List Program.");
    menu();
    command(); 
    
  }
  // This is the menu method that will print the list of commands
  public static void menu() {
    
    System.out.println("Here are the list of commands:");
    System.out.println("  -p : Print the List");
    System.out.println("  -e : Empty the List");
    System.out.println("  -x : Exit ");
    System.out.println("  -h : Print the Command List");
    
    
  }
  // this is the command function, depending on the answer will depend on what this function will do
  // thi function will call other functions as needed, or continue to add to list. 
  public void command(){
    String answer;
    System.out.print("Enter your item or command: ");
    answer = scan.nextLine();
    while( ! answer.equals("-x")) {
      if( answer.equals("-p")){
        printList();
      }
         if(answer.equals("-e")){
           emptyList();
     
         }
            if(answer.equals("-h")) {
              menu();
            }  
               // filled in the function below, and added break for -x to work.
               addToList(answer);
               break;
               }
  }
  
  // this is the add to list method that needs to be updated from the above
  public void addToList(String list) {
    shoppingList[count] = list;
    count++;
    command(); 
  }
    
  
  // this is the method that will empty the list 
  // Although currently it will add and selection as a value in the list. 
  public static void emptyList() {
    shoppingList = new String[ 10 ];
    count = 0;
    System.out.println("You just emptied your list");
   }
  
          
    
    // this is the method to print the list
    public static void printList(){
      for(int i=0; i<count;i++) {
        System.out.println((i+1) + " " + shoppingList[i]);
      }
    }
    
    // main method that will call the constructor and start program
    public static void main(String[] args) {
      new MyShoppingList1();
    }
}


Was This Post Helpful? 0
  • +
  • -

#5 blackcompe   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1159
  • View blog
  • Posts: 2,547
  • Joined: 05-May 05

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 04:11 PM

Suppose the following executes:

if(answer.equals("-e")){
           emptyList();
     
         }



So you've emptied the list. But, now answer still equals "-e," and then you add answer back into the list.

 addToList(answer);
               break;



That's why your list contains "-e" after emptying. You need to find a way to fix that. A do/while loop is a good option, but obviously, you don't want to go that route, so you could add the prompt and input statements right at the beginning of the loop, and when -e is entered you could call continue; to skip everything.

while(true) {
     System.out.print("Enter your item or command: ");
     answer = scan.nextLine();
     if(answer.equals("-e")) { emptyList(); continue; } //skip the rest of the loop body
     else if(answer.equals("-x")){ break; } //break out of loop
     .
     .
     .
}


This post has been edited by blackcompe: 17 November 2011 - 04:12 PM

Was This Post Helpful? 0
  • +
  • -

#6 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 04:12 PM

(At least) three things you need to do:

Add an "Add to List" command with the -z of your choice, -a?

Add the code that handles the new command. (call the addToList() method)

Write the addToList() method to add an item to the list. Where is the item identified? Is it passed to the method as part of the -z command handler? Or is the item identified by the user in the addToList() method? You don't want to add 'answer' to the list, because 'answer' is the user's command.

Give the basic design a bit more thought - answer "what has to happen when?" and you'll make sense of it.
Was This Post Helpful? 0
  • +
  • -

#7 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 05:45 PM

Ok, greg, so i am going to try black's solution first, then i will work out yours, as i have not worked a lot with the switch statement before. so here is my code using the switch statement, although i get an error on the switch(shop) it says that this is an incompatible type, found : java.lang.String, required: int. Should i change what it is using another method or cast.
Also i need to not allow for anything that begins with a - outside of the menu functions. although i feel like i am messing this up...What do you think.

public class MyShoppingList {
  private static String[] shoppingList;
  public static int count;
  private java.util.Scanner scan;
  
  // constructor for the program
  private MyShoppingList(){
    shoppingList = new String[10];
    scan = new java.util.Scanner(System.in);
    count = 0;
    System.out.println("Welcome to my Awesome Shopping List Program.");
    menu();
    command(); 
    
  }
  // This is the menu method that will print the list of commands
  public static void menu() {
    
    System.out.println("Here are the list of commands:");
    System.out.println("  -p : Print the List");
    System.out.println("  -e : Empty the List");
    System.out.println("  -x : Exit ");
    System.out.println("  -h : Print the Command List");
    
    
  }
  // this is the command function, depending on the answer will depend on what this function will do
  // thi function will call other functions as needed, or continue to add to list. 
  public void command(){
    String shop;
    do{
    System.out.println("Enter your item or command: ");
    shop = scan.nextLine();
    switch(shop) {
      case("-e"): emptyList(); break;
      case("-p"): printList(); break;
      case("-h"): menu(); break;
      default: addToList(shop);
    }
      System.out.println("Enter your item or command: ");
    }
     while(! shop.equals("-x"));{
      if( shop.equals("-")) {
        System.out.println("you cant enter that");
        menu();
      }
}
  }
  // this is the add to list method that needs to be updated from the above
  public void addToList(String list) {
     shoppingList[count] = list;
     count++;
     command(); 
  }
    
  
  // this is the method that will empty the list 
  public static void emptyList() {
    for(int i=0; i<=count; i++){
      shoppingList[i]=null;
    }
    count = 0;
    System.out.println("You just emptied your list");
   }
  
          
    
    // this is the method to print the list
    public static void printList(){
      for(int i=0; i<count;i++) {
        System.out.println((i+1) + " " + shoppingList[i]);
      }
    }
    
    // main method that will call the constructor and start program
    public static void main(String[] args) {
      new MyShoppingList();
    }
}


Was This Post Helpful? 0
  • +
  • -

#8 blackcompe   User is offline

  • D.I.C Lover
  • member icon

Reputation: 1159
  • View blog
  • Posts: 2,547
  • Joined: 05-May 05

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 06:53 PM

The new string-enabled switch statement is only available in JDK 1.7. If you don't have it change to consecutive if/else statements.
Was This Post Helpful? 0
  • +
  • -

#9 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 17 November 2011 - 11:04 PM

View Postblackcompe, on 17 November 2011 - 06:53 PM, said:

The new string-enabled switch statement is only available in JDK 1.7. If you don't have it change to consecutive if/else statements.



So back to my original code using while, if , if....

View PostGregBrannon, on 17 November 2011 - 04:12 PM, said:

(At least) three things you need to do:

Add an "Add to List" command with the -z of your choice, -a?

Add the code that handles the new command. (call the addToList() method)

Write the addToList() method to add an item to the list. Where is the item identified? Is it passed to the method as part of the -z command handler? Or is the item identified by the user in the addToList() method? You don't want to add 'answer' to the list, because 'answer' is the user's command.

Give the basic design a bit more thought - answer "what has to happen when?" and you'll make sense of it.



Ok i am going to try this, and work my way through this and post the code when its done. Although i am not suppose to add a command to signal you want to add to list, and i need to check to see if the - is entered and it isnt one of the letters defined an error message is displayed. I will write this up and let you see what i have. Thank you so much for the help with this, even just the little hints, really help.
Was This Post Helpful? 0
  • +
  • -

#10 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 02:10 AM

This is the first you've mentioned that you're not supposed to add another command. Don't leave out important details. So if the user types anything other than one of the recognized commands, the text will be accepted as a new item. That'll work. The default action out of the command handler will be to send the user's input to the method that adds the item. That's what you were trying to do earlier, and I didnt get it (should have been obious, sorry I missed it).

The concept will look something like:

// command handler
1. check user input for recognized commands and process the ones that are recognized
2. else - send unrecognized commands to addToList( command )

The addToList( command ) method will then become the garbage collector for all user inputs (commands) that fall through the command handler. Since you don't want to collect recognized commands as you were before, the addToList() method should only be called when the other if statements did not execute, so you need a string of if/else statements, and the call to addToList() will be the last else.

Sorry for the earlier misdirection.

This post has been edited by GregBrannon: 18 November 2011 - 03:12 AM

Was This Post Helpful? 1
  • +
  • -

#11 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 11:35 AM

Greg sorry, i was trying to troubleshoot each problem one at a time, so let me restart this with the specifics. I need to create individual methods for each so i can test each method individually. I also need to validate for errors, so if a "-" is entered and h,e,p, or x is not then an error is displayed, and the menu is reprinted to say to enter a different option. So basically anything that starts with a - and is not one of my options, anything else should be accepted as an item in the list. as well as i need to send an error for items that will be outside of the list length, so 10.
I have recreated my code with straight if/else statements, and again it eliminates my printing problem. But i cannot exit when i select -x. I though maybe i could use break, but it says that it must be inside of a if loop. Does that mean i need to tab out each one? also i commented out my validation for inproper menu selections but i don't think i did that part right.

public class MyShoppingList {
  private static String[] shoppingList;
  public static int count;
  private java.util.Scanner scan;
  
  // constructor for the program
  private MyShoppingList(){
    shoppingList = new String[10];
    scan = new java.util.Scanner(System.in);
    count = 0;
    System.out.println("Welcome to my Awesome Shopping List Program.");
    menu();
    command();
    
  }
  // This is the menu method that will print the list of commands
  public void menu() {
    
    System.out.println("Here are the list of commands:");
    System.out.println("  -p : Print the List");
    System.out.println("  -e : Empty the List");
    System.out.println("  -x : Exit ");
    System.out.println("  -h : Print the Command List");
    
    
    
  }
  // this is the command function, depending on the answer will depend on what this function will do
  // thi function will call other functions as needed, or continue to add to list. 
  public void command(){
    String answer;
    System.out.print("Enter your item or command: ");
    answer = scan.nextLine();
    String a = answer.substring(0);
    String b = answer.substring(1);
    if( answer.equals("-p")){
      printList();
      command();
      
    }
    if(answer.equals("-e")){
      emptyList();
      command();
      
      
    }
    if(answer.equals("-h")) {
      menu();
      command();
      
    }
    if(answer.equals("-x")) {
      System.out.println("thank you for playing"); 
      return;
    }
    // the below is what i need to validate.
    //else if(a.equals("-") && !b.equals("e") || !b.equals("h") || !b.equals("x") || !b.equals("p")) {
     //System.out.println("you can't enter that");
     // menu();
   //}
    // this needs to belong in the addToList Function.
       else {
        addToList(answer);
        command();
      
      
               }
  }
  
  // this is the add to list method that needs to be updated from the above
  public void addToList(String list) {
    shoppingList[count] = list;
    count++; 
  }
    
  
  // this is the method that will empty the list 
  // Although currently it will add the -e as value in the list. 
  public void emptyList() {
    shoppingList = new String[ 10 ];
    count = 0;
    System.out.println("You just emptied your list");
   }
  
          
    
    // this is the method to print the list
    public void printList(){
      System.out.println("Your Shopping List");
      for(int i=0; i<count;i++) {
        System.out.println((i+1) + ". " + shoppingList[i]);
      }
      
    }
    
    // main method that will call the constructor and start program
    public static void main(String[] args) {
      new MyShoppingList();
      //test1();
    }
    
    // this is my first test, to test the menu function.
    public static void test1() {
      MyShoppingList test1;
      test1 = new MyShoppingList();
      test1.menu();
    }
}



Was This Post Helpful? 0
  • +
  • -

#12 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 03:07 PM

Greg, so i think i figured it out, and got my validation and list length working correctly. I also have each method seperate and callable for testing purposes. If your still checking this thread, and want to see what it looks like, i would love your feedback on it. Just let me know.
Was This Post Helpful? 0
  • +
  • -

#13 GregBrannon   User is offline

  • D.I.C Lover
  • member icon

Reputation: 2250
  • View blog
  • Posts: 5,340
  • Joined: 10-September 10

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 03:46 PM

Sure, post it and we'll let you know.
Was This Post Helpful? 0
  • +
  • -

#14 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 04:02 PM

View PostGregBrannon, on 18 November 2011 - 03:46 PM, said:

Sure, post it and we'll let you know.



Here is my completed program, minus the individual test methods.

 public void command(){
    String answer;
    while(true) {
      System.out.print("Enter your item or command: ");
      answer = scan.nextLine();
      if( answer.equals("-p")){
        printList();
        continue;
      }
      if(answer.equals("-e")){
        emptyList();
        continue;
        
      }
      if(answer.equals("-h")) {
        menu();
        continue;
              
      }
      else if(answer.equals("-x")) {
        System.out.println("you have exited my Awesome shopping list program");
        break;
      }
      /**
       * This is the validation to item is not added to full list.
       */
      else if(count==10){
        System.out.println("sorry your list is full");
        continue;
      }
      
      else {
        addToList(answer);
      }
  }
  }
  
  /**
   * This is the add to list method, this also validates against errors, and a full list
   * this includes validation for anything that begins with a -
   * or a full list.
   * @param list is the item of the shopping list to add.
   */
  public void addToList(String list) {
    if(!list.matches("(?i)-.*")) {
        shoppingList[count] = list;
        count++;
      }
      else {
        System.out.println("you can't enter that");
        menu();
        
      }
      
    }
   
  /**
   * this is the method that will empty the list 
   * @param shoppingList is a new emtpy list.
   */
  public void emptyList() {
    shoppingList = new String[ 10 ];
    count = 0;
    System.out.println("You just emptied your list");
    
   }
  
          
    
    /** this is the method that will print the list.
      */
    public void printList(){
      System.out.println("Your Shopping List");
      for(int i=0; i<count;i++) {
        System.out.println((i+1) + ". " + shoppingList[i]);
      }
    }
    
    /**
     * main method that will call the constructor and start program
     * @param args is the command line argument.
     */
    public static void main(String[] args) {
      new MyShoppingList2();
      //test1();
    }
}


Was This Post Helpful? 0
  • +
  • -

#15 dj-wires   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 28
  • Joined: 12-October 11

Re: need to break out a function to a method in shopping list program

Posted 18 November 2011 - 04:24 PM

I notice its missing the first portion, but that hasnt changed from what it was, and i cant for the life of me find the edit button. lol.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2