Solved

# What is the best way to generate a random addition problem?

Posted on 2014-12-14
198 Views
Hi,

What is the best way to generate a random addition problem in android on a textview using only numbers 1-9?

8 + 7 = ?
0
Question by:Computer Guy

LVL 16

Expert Comment

Math.rand. No? Tried it?
0

LVL 3

Author Comment

Example?
0

LVL 26

Expert Comment

You want something like this:

Random r = new Random() ;
int first       = r.nextInt(9) + 1 ; // 1-9
int second = r.nextInt(9) + 1 ; // 1-9

String problem = Integer.toString(first) + " + " + Integer.toString(second) + " = ? " ;

Now show 'problem' in the text view.

Doug
0

LVL 24

Accepted Solution

Tomas Helgi Johannsson earned 500 total points
Hi!

To generate random number between 1 - 9 you can do this

Random rn = new Random();
int firstnum = rn.nextInt(9) + 1;
int secondnum = rn.nextInt(9) + 1;

Then simply present it using SetText method in TextView
http://www.java2s.com/Code/Android/UI/TextView.htm

I suggest you have a class that generates the math equation to solve and does the solving.

Regards,
Tomas Helgi
0

LVL 3

Author Comment

Also how can I generate the answer?

I have 3 buttons below the question I need to generate 2 random numbers and the other button needs to be the answer.
0

LVL 16

Expert Comment

BTW I meant Math.random() - got my languages wrong. ;)
0

LVL 16

Expert Comment

I need to generate 2 random numbers

All you need is

``````int r_1 = (int)(Math.random()*10);
int r_2 = (int)(Math.random()*10);
``````

Java.util.Random is for streams of numbers. Doesn't look like you need that.
0

## Featured Post

A short article about a problem I had getting the GPS LocationListener working.
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.