first array program quiz


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: first array program quiz

  1. #1
    Join Date
    Oct 2005
    Location
    Chicago
    Posts
    24

    first array program quiz

    I need to know whats wrong with the following lines of code and why. I had this questionn on a quiz today, couldn't answer

    int[] hws
    int mhw = hws.length
    int sum = 0
    for(int i = 0; i<hws.lengh; i++)
    sum = sum + hws[i]
    int avg= sum/mhw

    thanks
    I am a java n00b

  2. #2
    Join Date
    Aug 2005
    Posts
    43
    well, when you do the following: int mhw = hws.length, it will cause a compiler error since hws has not been initiated and its length is unknown, which also means that you would have compiler errors with the following also:
    i<hws.length
    hws[i]

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    And since you are dealing only w. integers here you will have a truncated, not
    rounded answer.

  4. #4
    Join Date
    Oct 2005
    Location
    Chicago
    Posts
    24
    what do you mean by a truncated, not rounded answer?
    and thanks for the help everyone is so smart

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Consider this:
    Code:
    int x=8;
    int y=3;
    int z=x/y; // (z=2,6666..... rounded: z=3;)
    but the answer is integer truncated so you get 2.0.
    To avoid this use doubles or add 0.5 like:
    int z=(double)x/(double)y + 0.5d;
    eschew obfuscation

Similar Threads

  1. Indexing an array
    By java50031 in forum Java
    Replies: 16
    Last Post: 10-17-2005, 02:26 PM
  2. Replies: 0
    Last Post: 04-24-2005, 01:13 PM
  3. Replies: 2
    Last Post: 04-15-2005, 10:06 PM
  4. Please help with running executable vb program.
    By Gordon Reichhardt in forum VB Classic
    Replies: 2
    Last Post: 01-08-2002, 11:06 AM
  5. How can I build copy protection into my program
    By W.Pierce in forum VB Classic
    Replies: 1
    Last Post: 12-11-2001, 09:28 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center