0

I need help making a program in java that lets you write a number in textField and then generate that amount of random numbers from 0-9 using i = (int) (Math.random() * 10.0). For example if I would write 5 in the textField the program would generate 5 random numbers from 0-9.

Thanks

3
  • Java != JavaScript - please clarify your chosen language - then read our How to Ask page to improve your question Commented Apr 10, 2016 at 18:33
  • 2
    have you done something yet? Commented Apr 10, 2016 at 18:33
  • 1. This question is too simple. 2. Java or javaScript? Commented Apr 10, 2016 at 18:33

3 Answers 3

1

Using the new Java 8 streams API:

int n = Integer.parseInt(myTextField.getText());
int[] random = ThreadLocalRandom.current().ints(0, 10).limit(n).toArray();
  • uses the current thread local random (recommended over creating a new Random instance)
  • creates a random stream of integers in the range [0..10) -> 0..9
  • Stream terminates after n numbers have been generated
  • the stream result is collected and returned as an array
Sign up to request clarification or add additional context in comments.

Comments

0

Ok since you want to use the Math.random() method try the following:

    int times = 5;//how many numbers to output

    for(int i = 0; i < times; i++)
    {
        System.out.println((int)(Math.random()*10));
        //you must cast the output of Math.random() to int since it returns double values
    }

I multiplied by 10 because Math.random() returns a value greater than or equal to 0.0 and less than 1.0.

2 Comments

Change your loop to i < times -- you are now printing 6 numbers
I just gave an example value to times i never said it will print five numbers. Anyway,i changed it to prevent future confusion thanks for pointing it out.
0
int x = value entered in textfield;
int generatedRandomNumber = 0;
java.util.Random rand = new java.util.Random();
for(int i=0 ; i<x ; i++) {
    generatedRandomNumber=rand.nextInt(10);//here you have your random number, do whatever you want....
}

1 Comment

Fix your indentation - it will make your code easier to read. Also, don't make your lines longer than 80 columns - just put the comment on another line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.