Results 1 to 3 of 3

Thread: HELP with homework assignment =[

  1. #1
    Join Date
    Oct 2008
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default HELP with homework assignment =[

    Me and my friend tried doing these two java homeworks for couple of hours and we cannot figure it out. is there some one who can help me with these two exercises ?
    They go as follows:

    Ex 1.

    Write an application that can hold five integers in an array. You can initialize the array elements with hard-coded values; you need not read them in from the keyboard. Display the integers from first to last (in terms of their order in the array, not sorted by value), and then display the integers from last to first (in terms of their order in the array).

    Ex 2.

    Write an application that than stores 10 prices in an array, such as $2.34, $7.89, $1.34, and so on. You can initialize the array elements with hard-coded values; you need not read them in from the keyboard. Display the sum of all the prices. Display all values less than $5.00. Calculate the average of the prices, and display all values that are higher than the calculated average value.

    This is what we have so far: We are both newbies on the java class and so far for the first exercise I have problems printing the numbers from the last to the first. For the second exercise i have a bunch of problems with no ideas how to fix them =[. thank u for your help.

    for exercise 1:
    public class JavaArray {

    /** Creates a new instance of JavaArray */
    public JavaArray() {
    }

    /**
    * @param args the command line arguments
    */
    public static void main(String[] args) {

    // Declare and create int array whose size is 5
    int[] ages = {5,6,7,2,4};


    // Display the value of each entry in the array
    for( int i=0; i<ages.length; i++ ){
    System.out.println ( "first to last number" + ages[i] );
    for( int i=5; i<ages.length; i-- ){
    System.out.println ( "first to last number" + ages[i] );
    }
    }
    }
    }



    -------------------------------------------------------------------------------------------------------
    for exercise 2:

    /// to find sum

    public class Arrays2{
    public static void main(String args[]){
    // this declares an array named fl with the type "array of int" and
    // initialize its elements
    float fl[] = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f, 3.6f, 2.9f, 6.2f, 5.5f, 9.8f };
    float sum = 0.0f;
    for(int i=0; i<= 9; i++)
    sum = sum + fl[i];
    // displays the sum
    System.out.println("The sum of the prices are= "+sum );
    //find average
    double average;
    for(int i=0;i<10; i++)
    {
    sum+=fl[i];
    }
    average=sum/10;
    System.out.println("Average is: "+average);
    int lessThan = 5;
    for (int lessThan = 1; lessThan < 5; i++) {
    System.out.println ("less than 5 :" + lessthan);
    }
    }
    }
    }

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    for( int i=5; i<ages.length; i-- ){
    How is it ever going to be >= ages.length if you decrement it? This would be an infinite loop, except that the condition is checked before the loop is ever executed, and i is already == ages.length, so it's never run. If you're displaying them backwards, what is the last element you display going to be?

    As for the latter question, you've pretty much got the idea, but you're taking the sum twice. The value you have is actually twice the sum. Whenever you have a function you're performing like 'sum' or 'mean', that takes some input(s) and produces an output, it's always wise to move it into a separate function/method. Functions serve to document bits of code (since they have names) and keep your code clean by separating the various operations out from one another. Function-calling overhead is minimal, so in any case you're likely to encounter, never be afraid to break up your code into as many small functions as you can. On the subject of code style, indentation will help enormously to keep your code readable. If you can't be bothered to do it yourself, don't neglect it — get an editor that will do it for you. I strongly recommend XEmacs (for Windows) or GNU emacs (for *nix, available through your favourite package manager).
    Code:
    public class Arrays2 {
        public static float sum(float[] vals) {
            float total = 0;
    
            for (float val : vals)
                total += val;
    
            return total;
        }
    
        public static float mean(float[] vals) {
            return sum(vals) / (float)vals.length;
        }
    
        public static float[] slice(int start, int end, float[] vals) {
    	// sanity checking
    	if (start < 0 || start > vals.length)
    	    throw new ArrayIndexOutOfBoundsException(start);
    	else if (end < 0 || end > vals.length)
    	    throw new ArrayIndexOutOfBoundsException(end);
    	else if (start > end)
    	    throw new ArrayIndexOutOfBoundsException("End occurs after start");
    
    	float[] ret = new float[end - start];
    
    	for (int i = start, count = 0; i < end; ++i)
    	    ret[count++] = vals[i];
    
    	return ret;
        }
    
        public static String prettyPrint(float[] vals) {
    	String ret = "[";
    	int i = 0;
    
    	for ( ; i < vals.length - 1; ++i)
    	    ret += vals[i] + ", ";
    
    	return ret + vals[i] + "]";
        }
    
        public static float[] lessThan(float limit, float[] vals) {
    	// there can never be more answers than inputs.
    	float[] answers = new float[vals.length];
    	int count = 0;
    
    	for (float val : vals)
                if (val < limit)
    		answers[count++] = val;
    
    	return slice(0, count, answers);
        }
    
        public static void main(String[] args) {
            float[] vals = {2.5f, 4.5f, 8.9f, 5.0f, 8.9f, 3.6f, 2.9f, 6.2f, 5.5f, 9.8f};
    
    	System.out.println("Sum: " + sum(vals));
    	System.out.println("Mean: " + mean(vals));
    	System.out.println("Less than five: " + prettyPrint(lessThan(5, vals)));
        }
    }
    Equivalent Haskell code:
    Code:
    main = do putStrLn $ "Sum: " ++ (show $ sum vals)
              putStrLn $ "Mean: " ++ (show $ mean vals)
              putStrLn $ "Less than five: " ++ (show $ filter (<5) vals)
      where mean xs = sum xs / fromIntegral (length xs)
            vals    = [2.5, 4.5, 8.9, 5.0, 8.9, 3.6, 2.9, 6.2, 5.5, 9.8]
    Last edited by Twey; 10-10-2008 at 10:51 PM.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. #3
    Join Date
    Oct 2008
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default

    Thanks for the great help =] thanks for your time and concern.
    it works perfect

Bookmarks

Posting Permissions

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