Results 1 to 4 of 4
  1. #1
    aldz24 is offline Member
    Join Date
    Aug 2016
    Posts
    21
    Rep Power
    0

    Default Adding another array to store the names of store as array of strings

    Hello

    What I need to do:
    Add another array to store the names of the stores. It should be an array of strings. Add the stores[] array to the parameters of each method.

    I'm reading this inputfile input.csv that has this values:

    Java Code:
        Name	 Number	   Store
        natto	   3	    Don Quijote
        eggs	   12	    Whole Foods
        shiitake	1	   farmer's market
        negi	   1	    farmer's market
        garlic	   5	       Costco
        umeboshi	1	     Don Quijote
    and the end it should be written to the output file output.csv.

    So my code should shows up like this with the store displayed and included:

    Java Code:
        Read from file: input4.csv
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 3
    
        Row        Name    Number    Store
         1        natto       3    Don Quijote
         2         eggs      12    Whole Foods
         3     shiitake       1    farmer's market
         4         negi       1    farmer's market
         5       garlic       5    Costco
         6     umeboshi       1    Don Quijote
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 1
    
        Enter name of item: BANANAS
        Enter number of items: 100
        Enter store of item: COSTCO
        Added row #7: BANANAS 100 COSTCO
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 3
    
        Row        Name    Number    Store
         1        natto       3    Don Quijote
         2         eggs      12    Whole Foods
         3     shiitake       1    farmer's market
         4         negi       1    farmer's market
         5       garlic       5    Costco
         6     umeboshi       1    Don Quijote
         7      BANANAS     100    COSTCO
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 2
    
        Enter the row number of the item you wish to delete: 3
        Deleting row #3: shiitake 1 farmer's market
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 3
    
        Row        Name    Number    Store
         1        natto       3    Don Quijote
         2         eggs      12    Whole Foods
         3         negi       1    farmer's market
         4       garlic       5    Costco
         5     umeboshi       1    Don Quijote
         6      BANANAS     100    COSTCO
    
        	GROCERY LIST MENU
        	 Enter 1 to Add
        	 Enter 2 to Delete
        	 Enter 3 to Display
        	 Enter 4 to Quit
        	Enter your choice: 4
    
        Wrote to file: output4.csv
    my code right now only shows the ability to add,delete,display the row, name and number except the store list. is there a way for me to follow this format above so it can :
    1. When I press 3, it would show the store list
    2. When I press 1 i can also Enter store of item: after entering the name and number of the item
    3. When i press 4 I can also delete the item listed including its store

    Here is the code I have to work with.

    Java Code:
        import java.util.Scanner;
        import java.util.InputMismatchException;
        import java.io.File;
        import java.io.FileNotFoundException;
        import java.io.PrintWriter;
        import java.lang.Integer;
          
       public class TestRun1 {
    
    
           public static String firstLineOfFile = ""; 
           
           /**
            * The main() Method Starts The Program.
            * 
            * @param commandlineArguments 1st argument is INPUT File, 2nd argument is OUTPUT File
            */
           public static void main(String[] commandlineArguments) {
              // Error Checking For 2 Command Line Arguments..
              if (commandlineArguments.length != 2) {
                 System.out.println("Please enter the INPUT file name as the 1st commandline argument.");
                 System.out.println("Please enter the OUTPUT file name as the 2nd commandline argument.");
                 System.out.println("Please enter exactly two (2) commandline arguments.");
              // Immediately terminates program
                 System.exit(1);   
              }// end of if
           // if no commandline argument errors, continue program
           
           // Declare and instantiate array of 100 Strings and Integers
              final Integer MAX_SIZE = new Integer(100);
              String itemNames[] = new String[MAX_SIZE];
              Integer itemNumbers[] = new Integer[MAX_SIZE];
           // Set size of grocery list to zero (0) items
              Integer size = new Integer(0);
           // read grocery items from file & store in arrays for grocery list
              try {
                 size = TestRun1.readFromFile(commandlineArguments[0],
                         itemNames, itemNumbers, size);
              } 
              catch (ArrayIndexOutOfBoundsException exception) {
                 System.out.print("ERROR: Too many items in input file. ");
                 System.out.println("Please limit to " + MAX_SIZE + " items.");
              // Immediately terminates program
                 System.exit(1);
              }
              
           // user's choice for Menu
              Integer choice = new Integer(0);
           // choice for ending program
              final Integer QUIT = new Integer(4);
           // if the user does NOT want to QUIT, keep looping
              while (false == choice.equals(QUIT)) {
              // get the user's choice
                 choice = TestRun1.displayMenu();
              // add grocery item
                 if (choice.equals(1)) {
                    size = TestRun1.add(itemNames, itemNumbers, size);
                 }
                 // delete grocery item
                 else if (choice.equals(2)) {
                    size = TestRun1.delete(itemNames, itemNumbers, size);
                 }
                     // display grocery item
                 else if (choice.equals(3)) {
                    TestRun1.display(itemNames, itemNumbers, size);
                 }
                     // error message
                 else if (false == choice.equals(QUIT)) {
                    System.out.println("ERROR: Please enter an integer in the range from 1 to 4");
                 }
              }// end of "while"
              
              // write to from grocery list array to OUTPUT file
              TestRun1.writeToFile(commandlineArguments[1], 
                 itemNames, itemNumbers,size);
           }// end of main() method
    
           /**
            * Displays the menu for the program and returns user's choice
            * 
            * @return the choice of the user (if error, returns 0)
            */
           public static Integer displayMenu() {
              // display menu
              System.out.println();
              System.out.println("\tGROCERY LIST MENU");
              System.out.println("\t Enter 1 to Add");
              System.out.println("\t Enter 2 to Delete");
              System.out.println("\t Enter 3 to Display");
              System.out.println("\t Enter 4 to Quit");
              System.out.print("\tEnter your choice: ");
              // get input from user
              Scanner keyboardInput = new Scanner(System.in);
              String userInput = new String("");
              Integer choiceOfUser = new Integer(0);
              //get next word from user (hopefully, it is a number)
              userInput = keyboardInput.next();
              try {
                 // non-integer input will throw an exception
                 choiceOfUser = Integer.parseInt(userInput);
              } 
              catch (NumberFormatException exception) {
                 System.out.println("ERROR: " + userInput + " is not a number!");
              }
              System.out.println();
              return choiceOfUser;
           }
    
           /**
            * Reads grocery items from a file and stores items in an array
            * 
            * @param inputFile is the INPUT File
            * @param itemNames2 is the array of item names in the grocery list
            * @param itemNumbers2 is the array of item numbers in the grocery list    
            * @param size is the number of items in Grocery List
            * @return the new size of the grocery list
            * @throws ArrayIndexOutOfBoundsException if array size is less than number of
            *         items in input file
            */
           public static Integer readFromFile(String inputFile, String[] itemNames2,
               Integer itemNumbers2[], Integer size) throws ArrayIndexOutOfBoundsException {
              // connect to file (does NOT create new file)
              File file = new File(inputFile);
              Scanner scanFile = null;
              try {
                 scanFile = new Scanner(file);
              } 
              catch (FileNotFoundException exception) {
                 // Print error message.
                 // In order to print double quotes("),
                 // the escape sequence for double quotes (\") must be used.
                 System.out.print("ERROR: File not found for \"");
                 System.out.println(inputFile + "\"");
              }
              // if made connection to file, read from file
              if (scanFile != null) {
              //first line of file is the headers, so don't store in the arrays
                 firstLineOfFile = scanFile.nextLine();
              
                 // keeps looping if file has more lines..
                 while (scanFile.hasNextLine()) {
                    // get a line of text..
                    String line = scanFile.nextLine();
                    
                 // divides each line by commas
                    Scanner lineInput = new Scanner(line).useDelimiter(",");
                 //get the name and count from one line in the file   
                    String name = lineInput.next();
                    String count1 = lineInput.next();
                   
                 //convert the string count to integer count2  
                    Integer count2 = 0; 
                    try{
                       count2 = Integer.parseInt(count1);
                    }
                    catch (NumberFormatException exception) {
                       System.out.println("ERROR: " + count1 + " is not a number!");
                       //if it is not an integer, then use zero (0) as default
                    }
                    //check for negative numbers
                    if(count2 < 0){
                    //change to positive integer
                       count2 = -count2;
                    }
                    
                    //assign and count2 to appropriate arrays
                    itemNames2[size] = name;
                    itemNumbers2[size] = count2;
                    
                    // increment size
                    ++size;
                 }
                 // In order to print double quotes("),
                 // the escape sequence for double quotes (\") must be used.
                 System.out.println("Read from file: " + inputFile);
              }// end of "if" for connecting to file
              return size;
           }
    
           /**
            * Adds a grocery item to an array
            * 
            * @param itemNames3 is the array of item names in the grocery list
            * @param itemNumbers3 is the array of item numbers in the grocery list    
            * @param listSize is the size of the grocery list
            * @return new size of the grocery list
            */
           public static Integer add(String[] itemNames3, 
           Integer[] itemNumbers3, Integer size) {
              // get item from user
              Scanner keyboard = new Scanner(System.in);
              System.out.print("Enter name of item: ");
              String name = keyboard.nextLine();
              System.out.print("Enter number of items: ");
              String count1 = keyboard.nextLine();
              
           //convert the string count to integer count2  
              Integer count2 = 0; 
              try{
                 count2 = Integer.parseInt(count1);
              }
              catch (NumberFormatException exception) {
                 System.out.println("ERROR: " + count2 + " is not a number!");
              //if it is not an integer, then use zero (0) as default
              }
           //check for negative numbers
              if(count2 < 0){
              //change to positive integer
                 count2 = -count2;
              }
                    
           //assign name and count2 to appropriate arrays at end 
              itemNames3[size] = name;
              itemNumbers3[size] = count2;
           
           //give feedback to user to let them know what is being addded
              System.out.println("Added row #" + (size + 1) + ": " 
                    + itemNames3[size] + " " + itemNumbers3[size]); 
           
              // add one to the size (one item to end of list)
              return size + 1;
           }
    
           /**
            * Deletes a grocery item from parallet arrays
            * 
            * @param itemNames4 is the item names in the grocery list
            * @param itemNumbers4 is the number of items in the grocery list
            * @param listSize is the size of the grocery list
            * @return new size of the grocery list
            */
           public static Integer delete(String[] itemNames4, 
           Integer[] itemNumbers4, Integer listSize) {
              // get user input
              System.out.print("Enter the row number of the item you wish to delete: ");
              Scanner keyboard = new Scanner(System.in);
              try {
                 // throws an exception if not an integer
                 Integer row = keyboard.nextInt();
                 // check for negative integers
                 if (row <= 0) {
                    System.out.println("ERROR: The row number cannot be negative or zero.");
                 }
                  // check for row number too big
                 else if (row > listSize + 1) {
                    System.out.println("ERROR: The row number is too big for the list.");
                 } 
                 else {
                 //convert row to an index in the array by subtracting one
                    Integer index = row - 1;
                    //give feedback to user to let them know what is being deleted
                    System.out.println("Deleting row #" + row + ": " 
                       + itemNames4[index] + " " + itemNumbers4[index]); 
                    
                    // delete item by shifting items on the right of the item to the left
                    for (int i = index; i < listSize; i++) {
                       itemNames4[i] = itemNames4[i + 1];
                       itemNumbers4[i] = itemNumbers4[i + 1];
                    }
                    // subtract one from the size (one item deleted from list)
                    --listSize;
                 }
              } 
              catch (InputMismatchException exception) {
                 System.out.println("ERROR: You must enter an integer to delete an item.");
              }
              return listSize;
           }
    
           /**
            * Displays a the grocery list
            * 
            * @param itemNames5 is the grocery list's item names
            * @param itemNumbers5 is the grocery list's item numbers
            * @param listSize is the size of the grocery list
            */
           public static void display(String[] itemNames5, 
           Integer[] itemNumbers5, Integer listSize) {
           // divides each line by commas
              Scanner lineInput = new Scanner(firstLineOfFile).useDelimiter(",");
           //get the two headers from the first line of the file   
              String header1 = lineInput.next();
              String header2 = lineInput.next();
              
           // display headings
              System.out.println("Row        " + header1 + "    " + header2);
              // loop through the array
              for (int i = 0; i < listSize; i++) {
                  // display grocery list items as a numbered list
                 System.out.printf("%2d     %8s     %3d\n", i+1, itemNames5[i], itemNumbers5[i]);
              }
           }
    
           /**
            * Write grocery list array to file
            * 
            * @param names is the grocery list names
            * @param numbers is the grocery list numbers
            * @param listSize is the size of the grocery list
            */
           public static void writeToFile(String outputFile, String[] names,
               Integer[] numbers, Integer listSize) {
              // "PrintWriter" is a Class Used To Write to A File.
              PrintWriter fileWriter = null;
              try {
                 /*
                  * Must use try-catch block, because PrintWriter may throw
                  * FileNotFoundException, which is a checked exception. This will connect
                  * to a file in the current directory. If the file does not exists, a new
                  * file will be created. If the file does exists, the file will be
                  * overwritten.
                  */
                 fileWriter = new PrintWriter(outputFile);
              } 
              catch (FileNotFoundException exception) {
                 // Print error message.
                 // In order to print double quotes("),
                 // the escape sequence for double quotes (\") must be used.
                 System.out.print("ERROR: File not found for \"");
                 System.out.println(outputFile + "\"");
              }
              // if file opened successfully, then below code executes..
              // continue program if writeToFile is not "null"
              if (fileWriter != null) {
              //write the headings to the first line of the file
                 fileWriter.println(firstLineOfFile);
              
                 // loop through list (grocery list) and write to file
                 for (int i = 0; i < listSize; i++) {
                    fileWriter.println(names[i]+","+numbers[i]);
                 }
                 // REMEMBER: always give feedback to the user!
                 System.out.println("Wrote to file: " + outputFile);
                 // WARNING: don't forget to close the file!
                 // will not write to file if not closed!
                 fileWriter.close();
              }// end of "if" statement for writeToFile
           
           }
    
        }// end of class

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: Adding another array to store the names of store as array of strings

    Do you have any specific questions about the changes you are trying to make?
    What happens when the code is compiled and executed?
    What is giving you problems?

    What have you tried?
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    benji2505 is offline Senior Member
    Join Date
    Sep 2014
    Location
    MA, USA
    Posts
    399
    Rep Power
    6

    Default Re: Adding another array to store the names of store as array of strings

    Do you have to solve this task this way?
    Let me give some food for thought: create a class "Food" with the parameters name, number, store and encapsulate it properly. Create a shoppingList array that takes a Food. In the Food constructor you automatically add the Food to the shopping list.
    When you read in the file you create a new instance of Food for each line. You also need a UI method to create a new instance of Food. Removing Food from the shoppingList<Food> array can be done by any parameter including array index.
    Any listing is easily done by looping through the array.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Adding another array to store the names of store as array of strings

    I'm guessing this is supposed to be parallel arrays.
    But I will ask, are you sure you shouldn't be resizing the arrays at some point?
    Three MAX_INT arrays seems a bit excessive.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

Similar Threads

  1. Replies: 4
    Last Post: 04-27-2013, 11:04 AM
  2. Creating an array to store JLabel names
    By alex.start in forum New To Java
    Replies: 3
    Last Post: 04-18-2013, 06:07 PM
  3. Store image in an 2D array
    By zenitis in forum New To Java
    Replies: 5
    Last Post: 12-23-2011, 03:53 PM
  4. how to store data in array
    By aconti in forum New To Java
    Replies: 7
    Last Post: 06-18-2011, 06:24 PM
  5. Replies: 1
    Last Post: 03-31-2009, 06:40 AM

Tags for this Thread

Posting Permissions

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