• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to get a random number

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,i ve made a class with a method to get integer random numbers.I used the Math.random class first to get a random number obviously and then the Math.ceil class to make the double number an integer.When i compile it it gives me an error "possible loss of precision".Found double,required int
My code is:

----------------------------------------------
private int number1;
public void setNumber1(int n1) {
n1 = Math.ceil(Math.random());
number1 = n1;
}

----------------------------------------------
Is there a better way to get a random number or how do i sort out this problem?Also,if i want to get only random numbers below 20(or any number) how can i do that?Any help will be really appreciated.Thanks
 
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
See this article: http://www.javaworld.com/javaworld/jw-01-2003/jw-0103-java101guide.html
 
Ranch Hand
Posts: 529
C++ Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You get the compiler error because you are trying to force a double into an int. The storage for a double is much larger than an int (because it has more precision), and cannot be forced without a type cast.
Try this:
int x = (int) (Math.random() * 20);

You can replace 20 with whatever you want. If you want to get a random number from 0 to 100, then use 100 instead of 20.
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Could you explain how this works?
int x = (int) (Math.random() * 20);
Thanks
 
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
Could you explain how this works?
int x = (int) (Math.random() * 20);
Thanks


(int) - Casts the next part (which is a double) into an int
Math.random() - Returns a random double between 0.0 and 1.0
* 20 - 0.0*20 = 0, 1.0*20 = 20, so a number between 0 and 20.
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
erm,for some reason the only number it gives me is 0.I have this program which asks people what the sum is(like 5+3) and i wanted the numbers to come up in random.I have 10 quesitons and all it does is ask 10 times the sum of 0+0 so dont know whats the problem.Can someone help?Thanks
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
erm,for some reason the only number it gives me is 0.


Are you using parentheses around the Math.round() and whatever you're multiplying it by? Otherwise, you'd be casting the 0.0-1.0 before the multiplication, which would usually (if not always) result in 0.

Edit: Nevermind the second part.
[ July 15, 2004: Message edited by: Darin Niard ]
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here it is:

public void setNumber1(int n1) {
n1 = (int) Math.random() * 100;
number1 = n1;
}

public void setNumber2(int n2) {
n2 = (int) Math.random() * 100;
number2 = n2;
}

public int getAnswer() {
int a = (number1 + number2);
answer = a;
return answer;
}
Cheers again for the help
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yep, just as I suspected. You are turning the Math.random() into an int, instead of the product of Math.random() and 100.
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
could you just explain this a bit for me please?I ve given you quite a hard time but thanks a lot for your help!
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You also don't need the two int parameters, for the same reason you didn't need it in getAnswer().
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
sorry but i am not making sense...Could you please type the correct code?Thanks
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
could you just explain this a bit for me please?I ve given you quite a hard time but thanks a lot for your help!


Ok, let's compare these two lines of code:

A. n1 = (int) Math.random() * 100;
B. n1 = (int) (Math.random() * 100);

In A, Math.random() returns a double that is always less than 1. Reading left to right, the program casts this double into an integer, which will result in 0, because when casting to an int, it drops all of the decimal places. So even (int)0.999999 will be 0. Then it multiplies the 0 by 100, which also results in 0.

In B, there are parentheses, so it executes the stuff in parens first, much like in math. So now, lets say Math.random() returns .71284 which is multiplied by 100, so you have 71.284, which is THEN cast to an int, with the result being 71.
[ July 15, 2004: Message edited by: Darin Niard ]
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
erm...sorry...i ve put it down the way you wrote and it still only gives me 0.Am gonna put the whole code down to see if you can find the error.Thanks(again)
public class MathsTest {

private int number1;
private int number2;
private int answer;

public MathsTest() {
number1 = 0;
number2 = 0;
answer = 0;
}

public void setNumber1(int n1) {
n1 = (int) (Math.random() * 100);
number1 = n1;
}

public void setNumber2(int n2) {
n2 = (int) (Math.random() * 100);
number2 = n2;
}

public int getAnswer() {
int a = (number1 + number2);
answer = a;
return answer;
}

public int getNumber1() {
return number1;
}

public int getNumber2() {
return number2;
}
}

import sheffield.*;

public class Maths1 {
public static void main (String[] args) {

String name;
int answer1;
EasyReader keyboard = new EasyReader();
System.out.println("What is your name?");
name = keyboard.readString();
System.out.println("Hello " + name);

MathsTest m = new MathsTest();
int total_correct_answers = 0;
for (int q = 1; q <= 10; q++) {
System.out.print("What is the sum of");
System.out.println(m.getNumber1() + "+" + m.getNumber2());
answer1 = keyboard.readInt();
if (answer1 == m.getAnswer()) {
System.out.println("Well done.Its the correct answer!");
total_correct_answers = (total_correct_answers + 1);
}
else {
System.out.println("Sorry.Wrong answer.The correct answer is " + m.getAnswer());
}
}
System.out.println("You got " + total_correct_answers + "out of 10");
}
}
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You never call anything but getNumber1 or 2, so they are still set to 0.

P.S. Use [code] tags next time.
[ July 15, 2004: Message edited by: Darin Niard ]
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
aha...sorry this is my first program with object oriented so am not very familiar with this...I thought by using:
public void setNumber1(int n1) {
n1 = (int) (Math.random() * 100);
number1 = n1;
}

that i had set number1 to a number but as it seems it does not happen.Then by calling getNumber1 it would get the number from number1.What am i doing wrong?
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
What am i doing wrong?



It's what you're not doing that's causing the problem. You're not invoking the setNumber methods. You need to do something like this:


[ July 16, 2004: Message edited by: Junilu Lacar ]
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It gives me an error "cannot resolve symbol: max" .And why do i need to use that max?thanks
 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
...I thought by using:
public void setNumber1(int n1) {
n1 = (int) (Math.random() * 100);
number1 = n1;
}

that i had set number1 to a number but as it seems it does not happen.



setNumber1() is a method, which defines a capability of a class. To actually execute the method, it must be invoked from the main thread of execution.


 
Junilu Lacar
Sheriff
Posts: 17644
300
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
It gives me an error "cannot resolve symbol: max" .And why do i need to use that max?thanks



OK, replace max with the literal value 10 then.

We use things like MAX to avoid "hard-coding" literal values, which are called "magic numbers". Magic numbers are bad because they make your program less readable (it doesn't convey the intent very well) and magic numbers tend to become duplicated in your code. To make your program more readable and avoid duplication, you do something like this:

[ July 16, 2004: Message edited by: Junilu Lacar ]
 
James Palmer
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
basically what i dont understand is that i get a number from the setNumber1 method and then in the main method i call the getNumber1() method which i thought would call the setNumber1 method to get the number itself.How am i supposed to call the setnumber method from the getnumber method in order to get a random number correctly instead of always getting a 0?
 
Darin Niard
Ranch Hand
Posts: 118
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by James Palmer:
i call the getNumber1() method which i thought would call the setNumber1 method to get the number itsel


I'm looking at your code, and your getNumber1() method never calls setNumber1()... so why would you think that it does?
 
reply
    Bookmark Topic Watch Topic
  • New Topic