Results 1 to 10 of 10
  1. #1
    Join Date
    Jul 2010
    Posts
    3
    Rep Power
    0

    Default Creating Static Methods

    I am very new to Java and am having a difficult time grasping the concepts being taught in my class. I think what keeps throwing me off is that the more I research the more I find that people do things differently. There are so many ways to do things how do I know if I am doing them right?

    I have an assignment due this week in which we make changes to our existing application. The application has two classes. In one of the classes there is an array of items. I need to create a static mehtod in the other class that totals the value of the elements in the array.

    Am I on the right track with the following code?

    //Caluclate order total and return value
    public static float orderTotal

    //Create for loop
    {
    for(int i = 0; i <items.length (); i++)
    {
    sum +=myArray [i];
    }

    If I am on the right track how does the store items class know what the items arrray is since it was specified in the cash register class?

  2. #2
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Default

    Not quite enough information in your post. If you can include the full code of the classes, it should help us help you.

    However, you do seem to be on the right track. I just can't be sure without more context.
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  3. #3
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    I need to create a static mehtod in the other class that totals the value of the elements in the array.
    That requirement says several things:
    1) the method takes an array as it argument
    2) it returns a number (the total)

    Your pseudo code is about right. Code it and try it.

    how does the store items class know what the items arrray is since it was specified in the cash register class?
    As Singing Boyo said, you don't show any classes to comment on.

  4. #4
    Join Date
    Jul 2010
    Posts
    3
    Rep Power
    0

    Default

    Sorry...I thought I had provided you with enough data. I am attaching what I have so far. There are several pieces to my assignment this week, but I am trying to address one at a time. Right now I am stuck on creating a static mehtod in the StoreItem class to calculate the total cost of all items in the array. Any help and/or explantion of why it should be done a certain way would be greatly appreciated! Thanks!

    Java Code:
    //Import scanner and number format for program use
    import java.util.Scanner;
    import java.text.NumberFormat;
    
    //Declare class
    public class CashReg3 {
    
        //Main method beings execution of Java application
        public static void main(String[] args) {
    
            //Create scanner object to obtain input from the command window
            Scanner input = new Scanner (System.in);
            
            //Create fmt1 object to format currency instances
            NumberFormat fmt1=NumberFormat.getCurrencyInstance();
                          
            //Create store item object for storing item information
            StoreItem si;  
                   
            //Declare variables and set to zero
            String name = " ";
            int quantity = 0;
            float price = 0;
            float total= 0;
            int itemNumber = 0;
            int number;
    
            //Determine size of array
            System.out.print ("How many items would you like to enter? : ");
            number = input.nextInt ();
            input.nextLine ();
    
            //Define array name and size
           StoreItem [] items = new StoreItem [number];
    
            //Begin loop
            for (int count = 0; count <items.length; ++ count)
            {
                //Continue loop until while value is meet
                do{
                    //Prompt user for input, read input, print blank line
                    System.out.print ("Please enter item " +(count + 1)+ "'s name: ");
                    name = input.nextLine();
                    System.out.println ();
                  }while(name.equals (""));
    
                //Prompt user for input, read input, print blank line
                System.out.print ("Please enter " + name + "'s item number: ");
                itemNumber = input.nextInt ();
                System.out.println ();
                    /*Check for positive number, if negative
                    prompt user to enter positive number
                    read new entry */
                    while (itemNumber < 0)
                    	{
    	                System.err.println ("Item number must be a positive number."
    	                + "Please try again.");
    	                System.out.print ("Please enter " + name + "'s item number: ");
    	                itemNumber = input.nextInt ();
                            System.out.println ();
                    	}
                //Prompt user for input, read input
                System.out.print ("Please enter the quantity of " + name + ": ");
                quantity = input.nextInt ();
                System.out.println ();
                    /*Check for positive number, if negative
                    prompt user to enter positive number and
                    read new entry*/
                    while (quantity < 0)
                        {
                        System.err.println ("Quantity must be a positive number. Please "
                         + "try again");
                        System.out.print ("Please enter the quantity of " + name + ": ");
                        quantity = input.nextInt();
                        System.out.println ();
                        }
    
                //Prompt user for input, read input
                System.out.print ("Please enter " + name + "'s price: $");
                price = input.nextFloat ();
                System.out.println ();
                    /*Check for positive number, if negative
                    prompt user to enter positive number
                    read new entry*/
                    while (price < 0)
                        {
                        System.err.println ("Price must be a positive number. Please "
                         + "try again");
                        System.out.print ("Please enter " + name + "'s price: $");
                        price = input.nextInt();
                        System.out.println ();
                        }
    
                //Fill array with data from current item
                items[count] = new StoreItem(name,itemNumber,quantity,price,total);
    
                //Clear buffer
                input.nextLine ();
    
             }// End loop
    
          // Loop through array and output appropiate values
            for (int count = 0; count < items.length; ++count)
            {
                System.out.println ("Item " +(count + 1)+ ":" + items [count].getName ());
                System.out.println ("Item Number: " + items [count].getItemNumber ());
                System.out.println ("Item Quantity: " + items [count].getQuantity ());
                System.out.println ("Item Price: " +fmt1.format (+ items [count].getPrice ()));
                System.out.println ("Total Cost: " +fmt1.format (+ items [count].getTotal ()));
             }//End loop
    
        }//End main method
    
    }//End class


    Java Code:
     //Set name for new class
    public class StoreItem {
    
        //Declare variables as private
        private String name;
        private int quantity;
        private float price;
        private int itemNumber;
        private float total;
    
        //Create a no parameter constructor, assign variables
       public StoreItem ()
        {
           name = " ";
           quantity = 0;
           price = 0;
           itemNumber = 0;
           total = 0;
    
         }
       
        //Create five parameter constructor, set default variables
       public StoreItem (String name, int itemNumber, int quantity, float price, float total)
        {
           this.name = name;
           this.itemNumber = itemNumber;
           this.quantity = quantity;
           this.price = price;
           this.total = total;
          
         }
    
          //Create getter and setter methods
    
           //Methods for name
            public String getName ()
             {
                 return name;
             }
    
            public void setName (String name)
             {
                  this.name = name;
             }
            // End methods for name
    
            //Methods for quantity
            public int getQuantity ()
             {
                 return quantity;
             }
    
            public void setQuantity (int quantity)
             {
                  this.quantity = quantity;
             }
            // End methods for quantity
    
             //Methods for price
            public float getPrice ()
             {
                 return price;
             }
    
            public void setPrice (float price)
             {
                  this.price = price;
             }
            // End methods for price
            
            //Methods for item number
            public int getItemNumber ()
              {
    	          return itemNumber;
          	  }
          	  
          	public void setItemNumber (int itemNumber)
          	  {
    	      	  this.itemNumber=itemNumber;
              }
            //End methods for item number
    
        	//Calculate total cost amd return value
        	public float getTotal ()
            {
               return total = quantity * price;
            }
    
            public void setTotal ()
            {
               this.total = quantity * price;
            }
        	// End method for calculate total
            
            //Calculate order total and return value using static method
            
            public static float orderTotal ()
            {
                //Create a for loop to iterate trough array
                
            }
    } // End class

    Moderator Edit: Code tags added
    Last edited by Fubarable; 07-11-2010 at 12:08 AM. Reason: Moderator Edit: Code tags added

  5. #5
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,266
    Rep Power
    25

    Default

    To work on the static method to total an array, write a small program that calls that method from its main() method. Define the array to total right there in the main() method:

    float[] anArray = new float[] {1.2, 2.3, 3.4, etc};

    and pass that to your method. You won't have to worry about inputting numbers while debugging the totaling method.

    When you get it to work, copy and paste it into the big program.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Hello, and welcome to the forum. I hope you don't mind that I edited your code and added code tags which should help make your posted code retain its formatting and be more readable.

    To do this yourself, highlight your pasted code (please be sure that it is already formatted when you paste it into the forum; the code tags don't magically format unformatted code) and then press the code button, and your code will have tags.

    Another way to do this is to manually place the tags into your code by placing the tag [cod&#101;] above your pasted code and the tag [/cod&#101;] below your pasted code like so:

    Java Code:
    [cod&#101;]
      // your code goes here
      // notice how the top and bottom tags are different
    [/cod&#101;]
    Best of luck, and again, welcome!

  7. #7
    Singing Boyo is offline Senior Member
    Join Date
    Mar 2009
    Posts
    552
    Rep Power
    6

    Thumbs up This stuck out... in a good way

    Quote Originally Posted by strugglingbeginner View Post
    There are several pieces to my assignment this week, but I am trying to address one at a time.
    Norm covered fairly well how to solve your problem, but I felt I had to say that this line stuck out to me. Thats a GREAT practice, keep doing it!;)
    If the above doesn't make sense to you, ignore it, but remember it - might be useful!
    And if you just randomly taught yourself to program, well... you're just like me!

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Cross-post: Static mehtods (Beginning Java forum at JavaRanch)

    The problem here is that you're asking unpaid volunteers to help you here, not paid consultants, and most of us mind if we take time away from work/lives/play to try to help someone only to find that we've provided a solution that was already provided in a cross-post hours ago. The proper thing to do is that if you feel you must cross-post, at least provide links in each cross-post to the other, so that folks don't waste time answering something already answered and so that folks can review all discussions that have already occurred.

  9. #9
    Join Date
    Jul 2010
    Posts
    3
    Rep Power
    0

    Default

    Moderator,

    As I stated I am new to Java and have never had to post any questions on forums like this before. I apologize for not using code tags and for posting my question on two different sites. I was not sure if I would receive any responses so I decided to post it in a few places. Know I now for future reference. :)

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. Replies: 8
    Last Post: 04-16-2012, 11:00 PM
  2. static methods
    By billq in forum New To Java
    Replies: 3
    Last Post: 12-30-2009, 02:34 PM
  3. Recursion with static and non static methods
    By sh4dyPT in forum New To Java
    Replies: 14
    Last Post: 03-27-2009, 06:56 AM
  4. Static methods
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 11-04-2007, 05:56 PM

Posting Permissions

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