DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2003
    Posts
    1

    Selecting an array value with a variable

    Hey,
    Im fairly new to Java, and im doing a course in it at the moment. I have been set some homework to do, but ive got a little stuck ...what i have to do is create a program that randomly generates numbers between 1 and 10, and then i have made an array which has 10 values, and say number 1 comes up in the random number generation, i want array [1] to have the number of times 1 appears in it. Ive came up with the following, but i keep getting errors ...i think there is a problem with defineing the variable i as a long, then the array as an integer...
    Code:
    int[] ar = {0,0,0,0,0,0,0,0,0,0};
    
    int a = 0;
    
    while (a<10)
    		{
    a++;
    
    long i = Math.round(Math.random()*10);
    
    ar[i] = i;
                    }
    
    
    	System.out.println(ar);
    with that code i get these errors:
    Code:
    found   : long
    required: int
    ar[i] = i;
       ^
    C:\Website Projects\Java Work\test 1\Document.java:14: possible loss of precision
    found   : long
    required: int
    ar[i] = i;
    if anyone could help me get this working i would be most greatful

    Thanks for your time,

    -Ross

    [ArchAngel added CODE tags]

  2. #2
    Join Date
    Mar 2003
    Posts
    834
    Declare i as an int and cast the result of Math.random() to an int.
    ArchAngel.
    O:-)

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
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links