DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 3 of 3
  1. #1
    Join Date
    Oct 2003
    Posts
    3

    Exclamation Help with random generator

    I need to generate a random number between -99 to 99, how do I code this? This is what I have so far, but it always comes out negative
    Random gererator=new Random();
    num1=Math.abs(generator.nextInt()) % 99 + -99;
    How do I fix it?

  2. #2
    Join Date
    Oct 2003
    Posts
    2
    this is not a fix for your code but it is how i would do it

    //this generates a random 0 or 1
    int b = (int) (Math.random()*100%2);

    //this generates a random number from 0 to 99
    int a = (int) (Math.random()*100%100);

    //this is how i turn it to a negative
    //but only when the random numberb is 0
    if(b==0){ a= a-(a*2);}

    //this prints a or -a (if you understand)
    System.out.println (a);

    hope it helps sorry if i have english trouble its not mi native languaje

  3. #3
    Join Date
    Mar 2003
    Posts
    834

    Lightbulb

    ...or you could generate a random number between 0 and 99 and then make another random decision as to whether it should be negative or not...
    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