Need a little hep with my java coding!
Page 1 of 1
johnchaser




Posts: 21

PostPosted: Sun, 27th Nov 2005 13:50    Post subject: Need a little hep with my java coding!
All right I'm supposed to make a class called Stock and have an arry the size of 100. I also need to create constructors accessors and mutators. Well I've already done this part.

Now the problem is I have implement Add, Search, Delete and Update functions.
Here's my partial code: Link
Back to top
sabalasa




Posts: 369
Location: EST
PostPosted: Thu, 1st Dec 2005 12:59    Post subject:
right.

Checked your code and here are my 2 cents.

First of all make you array dynamic. Instead of having an rigid array which size is immutable use a Collection...like a Set, List or Vector. These babys have dynamic size meaning that you can add and remove elements on the fly. With arrays when adding an element you have to first make a new array with the size of the old array + 1 and copy all elements from your old array to the new one and then add the new element. The same goes for deleting an element - make a new array with the size of the old array - 1 and copy the elments from the old array.

An example
Code:
import java.util.Vector;

class Element {
  private String name;
 
  public Element(String name) {
    this.name=name;
  }
  public void setName (String name) {
    this.name=name;
  }

  public String getName () {
    return name;
  }
}

class Main {
  public static void main (String[] args) {
     Vector v = new Vector();
     for (int i = 0; i<100; i++) {
        v.add(new Element("Foo"))
     }
     .
     .
     .
  }
}


Removing is as easy as this
Code:
v.removeElementAt(i);

where i is the index of the element.

Updating goes like this
Code:
Element e = (Element) v.elementAt(i);
e.setName("bar");


Inserting an element
Quote:
Element e = new Element("Baz");
v.insertElementAt(i, e);


And if you still want an array representation of your collection
Quote:
Element[] arr = (Element[]) v.toArray(new Element[v.size()]);


BTW: the code tag is buggy Razz Had to use quote tags after using code tag for 3 times Very Happy


rgds
Sabalasa
Back to top
johnchaser




Posts: 21

PostPosted: Thu, 1st Dec 2005 16:16    Post subject:
Thanks Saba, however, I'm prefer to use array and if you don't mind can you please show it with array instead? Thank you.
Back to top
sabalasa




Posts: 369
Location: EST
PostPosted: Fri, 2nd Dec 2005 18:40    Post subject:
Ok. you want it the hard way, don't you Very Happy

I've written an example app which does exactly the same things you need.
Here is the code for the array element:
Code:

public class Element {
   private String name;

   public Element(String name) {
      this.name=name;
   }
   public void setName (String name) {
      this.name=name;
   }
   public String getName () {
      return name;
   }
   /**
    * This method is invoked by JRE when there
    * is a need for a String representation of
    * the object (System.out.println() for example).
    * You can specify here which parameters represent your object.
    * The only parameter here is name.
    *
    * @see java.lang.Object#toString()
    */
   public String toString() {
      return name;
   }
}


and the main app
Code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
   /** Initialize the array with 10 spaces (change it for your needs) */
   private static Element[] elements = new Element[10];
   
   /** reusable method for showing the menu (I added 2 options - Show and Quit) **/
   private static void showMenu() {
      System.out.println("PLEASE MAKE YOUR SELECTION(A, S, D, H or Q):" );
      System.out.println("\n[A]dd new Record");
      System.out.println("[S]earch Record");
      System.out.println("[D]elete Record");
      System.out.println("[U]pdate Record");
      System.out.println("S[H]ow Records");
      System.out.println("[Q]uit");
      System.out.print("\n\nEnter Selection: ");
   }

   /** executes the program **/
   private static void execute() {
      try {
         boolean breakOut = false;
         InputStreamReader reader = new InputStreamReader(System.in);
         BufferedReader input = new BufferedReader(reader);
         while (!breakOut) { //loop until breakOut is true then exit
            showMenu(); // after each loop we need to show the menu again
            String inp = (input.readLine()).toUpperCase();
            if (inp.equals("")) {
               continue; //if the user entered an empty string then keep on asking
            }
            System.out.println("\nYou selected: " + inp);
            switch(inp.charAt(0)) { //determine what the user has entered
               case 'A': addRecord(); break;
               case 'S': searchRecord(); break;
               case 'D': deleteRecord(); break;
               case 'U': updateRecord(); break;
               case 'H': showRecords(); break;
               case 'Q': breakOut = true; //raise the breakOut flag
               default: continue; //in all other cases continue to loop
            }
         }
      } catch (IOException e) { // if some input/output exception occured
         e.printStackTrace(); //print it out and exit
      }
   }
   /** adds a record **/
   private static void addRecord () throws IOException {
      String name = getUserInput ("Enter the name for the new element: ");
      Element[] newArray = new Element[elements.length + 1]; //initialize a new array (old array length + 1)
      for (int i = 0; i < elements.length; i++) { //add all elements from the old array
         newArray[i] = elements[i];
      }
      newArray[newArray.length-1] = new Element(name); //add the new element to the end of the array
                                           //array indexes start from 0 and end with length - 1
                                           //fe. Arr[10] indexes are [0..9] not [1..10].
      elements = newArray; //assign new array
   }
   
   /** searches for a record **/
   private static void searchRecord () throws IOException {
      String name = getUserInput ("Enter the name of the element: ");
      for (int i = 0; i < elements.length; i++) {
         if (elements[i].getName().equals(name)) { //if the element has the same name as entered..
            System.out.println(elements[i] + " is at position " + (i+1)); //print it out (i starts from 0 therefore + 1)
            return; //and exit the method
         }
      }
      System.out.println("Could not find an element with the name " + name); //tough shit :P
   }
   /** deletes a record **/
   private static void deleteRecord () throws IOException {
      int idx;
      while (true) { //ask for the index
         idx = validateInput(getUserInput("Enter the index of the element: "));
         if (idx > 0)
            break;
      }
      Element[] newArray = new Element [elements.length - 1]; //create a new array (old size - 1)
      int newIdx = 0; //initialize an index for the new array.
                  //Note that this one will not be increased when we hit the element with the index the user entered
      for (int i = 0; i < elements.length; i++) { //copy all other elements
         if (i != idx - 1) { //if its not the index the user entered.
                        //array indexes start with 0 and therefore we need to substract 1 from the number the user entered.
            newArray[newIdx] = elements[i]; //just copy the element
            newIdx++; //and increase the new index
         }
      }
      elements = newArray; //assign new array
   }
   /** updates a record **/
   private static void updateRecord () throws IOException {
      int idx;
      String newName;
      while (true) { // get the index
         idx = validateInput(getUserInput("Enter the index of the element you want to update: "));
         if (idx > 0) { //and the name
            newName = getUserInput("Enter new name for the element: ");
            break;
         }
      }
      Element e = elements[idx-1]; //get the element from the array (-1 again from the user input)
      e.setName(newName); // update the name
   }
   /** prints out the records **/
   private static void showRecords() {
      for (int i = 0; i < elements.length; i++) {
         System.out.println((i+1) + "-" + elements[i]); //i+1 because i starts from 0. Uses the toString method from the Element class
      }
   }
   /** reusable method for validating user input and convert it to int**/
   private static int validateInput(String input) {
      int ret = -1; // -1 represents invalid input
      if (!input.equals("")) {
         try {
            ret = Integer.parseInt(input); //try to parse the input into int
            if ((ret - 1) < 0 || (ret - 1) >= elements.length) { //check if the number is between the array capacity
               System.out.println ("Index must be between 1 and " + elements.length + "!");
               ret = -1;
            }
         } catch (NumberFormatException nfe) { //if parsing failed
            System.out.println ("Not an integer: " + input);
         }
      }
      return ret;
   }
   
   /** reusable method for getting user input **/
   private static String getUserInput(String displayString) throws IOException {
      String ret = null;
      InputStreamReader reader = new InputStreamReader(System.in);
      BufferedReader input = new BufferedReader(reader);
      while (true) { //infinite loop
         System.out.print (displayString);
         ret = input.readLine();
         if (!ret.equals("")) //if the user enters an empty string then ask again
            break; //break out the infinite loop
      }
      return ret;
   }

   public static void main(String args[]) {
      for (int i = 0; i < elements.length; i++)
         elements[i] = new Element("Foo" +( i + 1));
      execute();
   }
}


It took me about half an hour and I also included comments because I do not know your current skill with Java.

have fun, and copy/paste this code and you should be just fine Very Happy


rgds
Sabalasa
Back to top
[sYn]
[Moderator] Elitist



Posts: 8374

PostPosted: Fri, 2nd Dec 2005 20:26    Post subject:
Good man for helping Smile!
Back to top
sabalasa




Posts: 369
Location: EST
PostPosted: Fri, 2nd Dec 2005 21:06    Post subject:
NP!

I'm a Java senior programmer and a mentor for beginners anyway Razz


rgds
Sabalasa
Back to top
sabalasa




Posts: 369
Location: EST
PostPosted: Fri, 2nd Dec 2005 21:11    Post subject:
Oh, by the way johnchaser...

Just analyse the code, try to decompose it and try understand what some piece of code does and then...if you really want to be a Java guru ... expand this logic. For example create methods for sorting the array and for swapping element positions etc.

Then you're ready to go for harder problems Wink


rgds
Sabalasa
Back to top
Page 1 of 1 All times are GMT + 1 Hour
NFOHump.com Forum Index - Programmers Corner
Signature/Avatar nuking: none (can be changed in your profile)  


Display posts from previous:   

Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB 2.0.8 © 2001, 2002 phpBB Group