Random number groups - java

I am making app where shows me on display random set of numbers. And here is my question becouse my code looks like that:
tv1 = (TextView) findViewById(R.id.textView);
btn1 = (Button) findViewById(R.id.button);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Random rand = java.util.concurrent.ThreadLocalRandom.current();
new java.util.Timer().scheduleAtFixedRate(new java.util.TimerTask() {
#Override
public void run() {
tv1.setText(rand.nextInt(6) + "-" + rand.nextInt(6) + "-" + rand.nextInt(6));
}
}, 0, 3000);
}
});
}
}
Is it possible that the application instead of numbers from 6 to 0 would take ready sets of numbers that I create?

Implement the method given below inside your activity class and you can use it to achieve your requirements:
// To get the numbers from 0 to 6 use upperBound as 7.
private static String getResult(int lowerBound, int upperBound){
final ThreadLocalRandom rand = ThreadLocalRandom.current();
List<Integer> list = new ArrayList<Integer>();
int number;
for(int counter = 0; counter < 3;counter++){
number = rand.nextInt(lowerBound, upperBound);
while(list.contains(number)) {
number = rand.nextInt(lowerBound, upperBound);
}
list.add(number);
}
Collections.sort(list); //Sorts the list
return list.get(0) + "-" + list.get(1) + "-" + list.get(2);
}
In your TextView tv1 inside run() method; simply call this method, something like:
tv1.setText(getResult(0, 7)); // Remember in the sequence; 0 is inclusive and 7 is exclusive.
You can see the sample run here.

If you want to draw random numbers from a List, you can use rand.nextInt(list.size()) to get a random index to draw a number from, as the upper bound argument for nextInt is exclusive.
final java.util.List<Integer> numbers = java.util.Arrays.asList(1, 4, 534, 94);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final java.util.Random rand = java.util.concurrent.ThreadLocalRandom.current();
new java.util.Timer().scheduleAtFixedRate(new java.util.TimerTask() {
#Override
public void run() {
tv1.setText(numbers.get(rand.nextInt(numbers.size())) + "-" + numbers.get(rand.nextInt(numbers.size())) + "-" + numbers.get(rand.nextInt(numbers.size()));
}
}, 0, 3000);
}
});
}
}

Related

How can I generate different random numbers regularly in 4 second?

I'm trying to write a bingo game code. I want to produce 70 random numbers that change every 4 seconds.
I created a countdowntimer and created a random number in 4 seconds by defining a runnable into the finnish section in countdowntimer. But these random numbers may not be different from each other.
Handler handler;
Runnable run;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Random random = new Random();
int i = random.nextInt(70);
Random random2 = new Random();
int z = random2.nextInt(70);
int y =random2.nextInt(70);
int x =random2.nextInt(70);
int w =random2.nextInt(70);
int q =random2.nextInt(70);
int v =random2.nextInt(70);
int m =random2.nextInt(70);
int n =random2.nextInt(70);
int l =random2.nextInt(70);
final TextView textView3 = (TextView) findViewById(R.id.textView3);
final TextView textView4 = (TextView) findViewById(R.id.textView4);
final TextView textView5 = (TextView) findViewById(R.id.textView5);
final TextView textView6 = (TextView) findViewById(R.id.textView6);
final TextView textView7 = (TextView) findViewById(R.id.textView7);
final TextView textView8 = (TextView) findViewById(R.id.textView8);
final TextView textView9 = (TextView) findViewById(R.id.textView9);
final TextView textView10 = (TextView) findViewById(R.id.textView10);
final TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
final int a = Integer.parseInt(textView3.getText().toString());
final int b = Integer.parseInt(textView4.getText().toString());
final int c = Integer.parseInt(textView5.getText().toString());
final int d = Integer.parseInt(textView6.getText().toString());
final int e = Integer.parseInt(textView7.getText().toString());
final int f = Integer.parseInt(textView8.getText().toString());
final int g = Integer.parseInt(textView9.getText().toString());
final int h = Integer.parseInt(textView10.getText().toString());
textView9.setText("" + z);
textView10.setText(" "+ y);
textView8.setText(" "+ x);
textView7.setText(" "+ w);
textView6.setText(" "+ q);
textView5.setText(" "+ l);
textView4.setText(" "+ m);
textView3.setText(" "+ n);
CountDownTimer ct0 = new CountDownTimer(60000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Remaining time: " + millisUntilFinished / 1000);
}
#Override
public void onFinish() {
}
}.start();
CountDownTimer ct1 = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
int[] numbers = new int[70];
Random random = new Random();
int i = random.nextInt(70);
TextView textView2 = (TextView) findViewById(R.id.textView2);
textView2.setText("Lucky number: " + i);
if ( i == a) {
textView3.setText("ok");
} else if (i == b) {
textView4.setText("ok");
} else if (i == c) {
textView5.setText("ok");
} else if (i == d) {
textView6.setText("ok");
} else if (i == e) {
textView7.setText("ok");
} else if(i == f) {
textView8.setText("ok");
} else if (i == g) {
textView9.setText("ok");
} else if (i == h) {
textView10.setText("ok");
}
handler.postDelayed(this, 4000);
}
};
handler.post(run);
}
}.
start();
}
For 60 seconds, I want to create 70 different numbers every 4 seconds and match these numbers to the other 8 variables. I'd appreciate it if you could help. thanks.
I can give to you a way to do this, to avoid what you are saying :
But these random numbers may not be different from each other.
That's obvious because you do not control it.
I'd say to create a a Set<Integer> of your size that is 70, so you can fill this array doing a simple for loop.
for (int i = 0; i<70; i++) yourSetList.add(i);
Then a good way to "simulate" the bingo is shuffling the list, so you can use
Collections shuffle
Then you can generate a random like this :
Random random = new Random();
int random = random.nextInt(yourSetList.size()) + 1;
Then use random as an index
yourSetList.get(random);
Make sure you remove it from the list to avoid your initial problem
yourSetList.remove(random);

How to set click limit of clicking a button? click limit is equal to score over 5

How can I set a limit of clicking a button? The number of click is equal to score % 5.Example score is equal to 15 the number of click limit is equal to 3 how can I do that? my codes is not working
int score = 0;
int help = score % 5;
if (score == help) {
helpbtn.setEnabled(false);
} else {
helpbtn.setEnabled(true);
}
I put it inside of
public void onClick(View v) { }
If in the example limit is 3, then :
if(help>0)
{
//logic;
help--;
}
you can add it in else block.
I think I understand what you need now. I've made some assumptions. I added a separate button to submit answers and I added a boolean that is always true for now. I did manage to use modulo in this version though. Hope this helps.
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private int score = 0;
private int help = 0;
private boolean answerCorrect = true; // dummy set always true for now
private Button answerButton = null;
private Button hlpbtn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answerButton = (Button)findViewById(R.id.button_answer);
answerButton.setOnClickListener(this);
hlpbtn = (Button)findViewById(R.id.button_help);
hlpbtn.setOnClickListener(this);
hlpbtn.setEnabled(false);
}
#Override
public void onClick(View view) {
if(view.getId() == R.id.button_answer) {
if(answerCorrect) {
if((++score % 5) == 0) {
++help;
}
if((help > 0) && !hlpbtn.isEnabled()) {
hlpbtn.setEnabled(true);
}
}
Log.d("Quiz", "score = " + score + ", help = " + help);
} else if(view.getId() == R.id.button_help) {
if(--help <= 0) {
hlpbtn.setEnabled(false);
Log.d("Quiz", "help button disabled");
}
Log.d("Quiz", "help pressed, " + help + " remaining");
}
}
}
It sounds like you want 15 / 5 instead of 15 % 5.
15 / 5 == 3, whereas 15 % 5 == 0.
15/5 =3. Try this, this will help you to click a button 3 times.
%it gives remainder. Ie --->15%5=0

Check if user decided correct

I'm currently working on a school project (a small android game) and so far I've written a code which generates a random equation 2 seconds after the activity InGame is launched and displays it in a textview. Another 5 seconds later, the second equation is generated and displayed in a different textview. Now the user has to decide if the second equation has a bigger result than the first one by either pressing the button bigger or smaller. If it was correct, the next equation should be displayed and it would go on like this until the user decided wrong.
Here is my code so far:
(Code for the first equation):
// Generate random equation and display it in textview
String[] operationSet = new String[]{"+", "-", "/", "*"};
String equation;
static double doubleAnswer1;
public void start1() {
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(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation = "";
for (int i = 0; i < numOfOperations; i++) {
equation += numbers.get(i);
equation += operations.get(i);
}
equation += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView_first_equation);
TextEquation.setText(equation);
// Evaluate the result of the equation
double doubleAnswer1 = eval(equation);
String stringAnswer = Double.toString(doubleAnswer1);
TextView textAnswer = (TextView)findViewById(R.id.textView4);
textAnswer.setText(stringAnswer);
}
(Code for second equation (basically same as for first equation except the name of the strings and doubles are different)):
String equation2;
static double doubleAnswer2;
public void start2() {
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(4)];
operations.add(operation);
}
int numOfNumbers = numOfOperations + 1;
List<Integer> numbers = new ArrayList<>();
for (int i = 0; i < numOfNumbers; i++) {
int number = random.nextInt(10)+1;
numbers.add(number);
}
String equation2 = "";
for (int i = 0; i < numOfOperations; i++) {
equation2 += numbers.get(i);
equation2 += operations.get(i);
}
equation2 += numbers.get(numbers.size() -1);
TextView TextEquation = (TextView)findViewById(R.id.textView3);
TextEquation.setText(equation2);
// Evaluate the result of the equation
double doubleAnswer2 = eval(equation2);
String stringAnswer = Double.toString(doubleAnswer2);
TextView textAnswer = (TextView)findViewById(R.id.textView_result2);
textAnswer.setText(stringAnswer);
}
And here is my onCreate code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ingame);
// Display first equation 2 seconds after the activity is launched
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
start1();
}
}, 2000);
final Handler handler2 = new Handler();
handler2.postDelayed(new Runnable() {
#Override
public void run() {
start2();
}
}, 7000);
// Check if user was right or wrong
final Button buttonBigger = (Button)findViewById(R.id.button_bigger);
final Button buttonSmaller = (Button)findViewById(R.id.button_smaller);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(v.equals(buttonBigger) && doubleAnswer1 < doubleAnswer2) {
Log.v("TAG", "you are right");
} else if(v.equals(buttonSmaller) && doubleAnswer1 > doubleAnswer2) {
Log.v("TAG", "you are right");
} else {
Log.v("TAG", "you are wrong");
}
}
};
buttonBigger.setOnClickListener(listener);
buttonSmaller.setOnClickListener(listener);
}
The app launches correctly and it also displays the first and second equation, but when I press one of the button, it tells me in the logcat you are wrong but I decided 100% correct. However if I debug the app, it tells me that doubleAnswer1 and doubleAnswer2 are both = 0. That's why it all ways tells me 'you are wrong'. I don't know how to fix this, maybe I need to store the doubleAnswer1 and doubleAnswer2 somewhere.
I really don't know what to do, so it would really help me if someone has an idea what to do.
If anything is unclear in my question, feel free to ask and I will try to clarify the problem.
Thank you in advance for your help!
I think your problem lies here:
double doubleAnswer1 = eval(equation);
I did a quick internet search and did not find any native function called eval(). Instead you should look into Script Engine Manager for java:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String foo = "40+2";
System.out.println(engine.eval(foo));
or exp4j which is shown here:
Executing math equation in Android
Edit:
change the following:
double doubleAnswer1 = eval(equation);
to:
doubleAnswer1 = eval(equation);
Similarly do the same for doubleAnswer2

Not able to display very large calculation value in editext

private TextView info;
private EditText input;
private Button getInfo;
long answer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInfo = (Button) findViewById(R.id.button1);
getInfo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
input = (EditText) findViewById(R.id.editText1);
String s2 = input.getText().toString();
long inputNumber = Integer.parseInt(s2);
for (int i = 0; i <= inputNumber; i++) {
answer = fibonacci(i);
}
input.setText(answer + "");
}
});
}
public static long fibonacci(long n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
I made a program which generates fibonacci series for the number I give input through edit text and display the output value in edittext .Issue is when I enter 30 it generates fibonacci series but when I enter 50 or 100 app does not respond and stops .
I think it is because you have a lot of calculation on UI thread.
Try calculate it in AssyncTask, for example.

how to generate unrepeating random layouts

public class Music extends Activity {
private int [] layouts = {
R.layout.question_selector,
R.layout.question_selector2,
R.layout.question_selector3,
R.layout.queston_selector4,
R.layout.question_selector5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
int i = layouts.length;
Random r = new Random();
while (--i > 0) {
int j = r.nextInt(i + 1);
//swap values
int temp = layouts[j];
layouts[j] = layouts[i];
layouts[i] = temp;
}
setContentView(layouts[i]);
}
}
Here's what i have done so far: it works just fine, but I have notice that there are times that some layouts are shown over and over again. What I want is that when I press the button and it generates a layout randomly, the next time I'll press the button again it should not repeat the layout that had been shown before. How can I do such thing?
You can create an arrayList and then shuffle it instead of an array with Random, this will make it random but only use every item once
EDIT, code example:
ArrayList<int> mArrayList = new ArrayList<int>;
//OR ArrayList<int> mArrayList = new ArrayList<int>(Arrays.asList(mOrdinaryArray));
mArrayList.put(R.blabla.blabla);
mArrayList.put(R.blabla.blablatwo);
Collections.shuffle(mArrayList);
Log.d(TAG, "output after shuffle: " + mArrayList);

Categories