Issue
I'm working on a school project in Android Studio and I've already asked here how to randomly generate equations, like 10+48*4. Someone suggested me this code to generate the equations:
String[] operationSet = new String[]{"+", "-", "/", "*"};
public void testGenerateRandomEquations() {
Random random = new Random();
int numOfOperations = random.nextInt(2) + 1;
List<String> operations = new ArrayList<>();
for (int i = 0; i < numOfOperations; i++) {
String operation = operationSet[random.nextInt(3)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(Integer.MAX_VALUE) - random.nextInt(Integer.MAX_VALUE);
numbers.add(number);
}
//Now you've the list of random numbers and operations. You can further randomize
//by randomly choosing the number and operation from those list.
}
But now I don't know how to display the generated equation. How can I display the equation for example in a TextView? Maybe I'm just too dumb to understand but it would be nice if someone could help me :)
Here is the link to the original post: http://stackoverflow.com/a/39960279/6949270
Solution
All you have to do is to loop over the two lists - numbers
and operations
and concatenate them into a single string:
String equation = null;
for (int i = 0; i < numOfOperatrions; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1); //Add the last number to the equation
The last line is needed because there are more numbers (one more) than operations.
It is better to use StringBuilder
than String
when concatenating strings, but for short strings it's OK.
EDIT - Why does it work?
We are concatenating String
with an Integer
, using the +
operator.
The JAVA compiler converts in this case the Integer
into a String
, so no other casting is required.
Answered By - TDG
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.