Random boolean generator for android - android

I am trying to create a random (50/50) chance of a case A or case B happen in android and I need it to be as simple and as resource efficient as possible. I've looked through stackoverflow but all I find for random boolean is in C++?
Would appreciate if someone could give me a suggestion as to how to do this, whether with boolean or with strings/integers (since I was told that booleans is a primitive).
I tried the following
public static boolean getRandomBoolean() {
return Math.random() < 0.5; }
boolean atrg = getRandomBoolean();
if (atrg = true)
{ Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show(); }
else if (atrg = false)
{ Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show(); }
But in nearly every case, I tested (>20x), its TRUE?. This is likely a stupid question but is getRandomBoolean a boolean or an int/double? Sorry, I'm very new to android, as you probably guessed.

Your random generator is fine, but your toast displaying the result is not.
The problem is in the if-statement where you use a single equals sign (=) which is an assignment. The result of this assignment will be true and thus it will never show the "FALSE" toast.
Try this instead.
boolean atrg = getRandomBoolean();
if (atrg) {
Toast.makeText(cxt, "TRUE", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(cxt, "FALSE", Toast.LENGTH_SHORT).show();
}

This is not how you check boolean in if. = is the assignment operator and == is used for comparison. You should check like:
if(atrg == true)
or in case of boolean it is simply:
if(atrg)
Your statement:
if(atrg = true)
assigns atrg with true and you never get a false case.

Just use Math.random(), it will return a value between 0 and 1.. Example below:
public static boolean getRandomBoolean() {
return Math.random() < 0.5;
}
public static void main(String[] args) {
System.out.println(getRandomBoolean());
}

Related

Android double return

http://imgur.com/DzTRV2D
In android application i have code like below
private boolean isSpinnerNotChoose(Spinner spinner)
{
if(spinner.getSelectedItem().toString().equals(""))
{
return false;
}
return true;
}
But after many tries even if condition is completed it firstly enter on return false and later anyway debbugger goes on return true (If something stays after brackets its skipped but return true always is done. In link is image how its look after if is completed.
Anyone can answer me for that situation ?
Thanks in advance :)
Better use a boolean and return the boolean once.
The boolean is initially set to true.
It will remain true, if no match happens.
If there's a match, it will change to false.
Then the boolean will be returned (true if no match happens, false if there's a match).
No ghost responses.
I also added a trim(), to cut away the eventual trailing spaces.
Try:
private boolean isSpinnerNotChoose(Spinner spinner)
{
boolean myValue = true; // default return value
if(spinner.getSelectedItem().toString().trim().equals(""))
{
myValue = false;
}
return myValue; // return once and for all
}

Android - How to check if an achievement has been unlocked

I have some incremental achievements on my game and i want to check if one of them is already unlocked. How can i do that?
Originaly i used this method:
getGamesClient().incrementAchievement(achievement, increment);
Then i tried to use this:
mHelper.getGamesClient().incrementAchievementImmediate(new OnAchievementUpdatedListener()
{
#Override
public void onAchievementUpdated(int statusCode, String achievementId)
{
// TODO: Check if the achievement got unlocked
}
}, achievement, increment);
Is this the right way to do what i want? Is there a better way?
I only got two statusCode values on my tests.
Value: 5 = STATUS_NETWORK_ERROR_OPERATION_DEFERRED
Value: 0 = STATUS_OK
Can some one help me with this?
Thanks
Declare this inner class:
class AchievementClass implements ResultCallback<Achievements.LoadAchievementsResult> {
#Override
public void onResult(LoadAchievementsResult arg0) {
Achievement ach;
AchievementBuffer aBuffer = arg0.getAchievements();
Iterator<Achievement> aIterator = aBuffer.iterator();
while (aIterator.hasNext()) {
ach = aIterator.next();
if ("The Achievement Id you are checking".equals(ach.getAchievementId())) {
if (ach.getState() == Achievement.STATE_UNLOCKED) {
// it is unlocked
} else {
//it is not unlocked
}
aBuffer.close();
break;
}
}
}
}
And use it like so:
Games.Achievements.load(ApiClient, false).setResultCallback(new AchievementClass());
This will get achievement data for the currently signed in player, go through all the achievements, and when it reaches the achievement you're concerned with, it will check if it is unlocked.

Standalone return expression explanation

I was online looking at some android coding examples and i came across a method that had a return expression by itself,and i was wondering if someone could explain what that means.
Here is the code sample:
if(tempText.getText().length() ==0){
Toast.makeText(this, "Please enter a valid number", Toast.LENGTH_LONG).show();
return;
}
This is the If condition which checks for the length of the text which is "0" or not. If its "0" then it will show the Toast message and will return from or exit from the if loop an no further execution will processed.
using if condition you are checking for the length of text, if it is 0 then you are showing Toast
Using a return Keyword within a class, with a method
A method returning nothing
public void Void_Method()
{
<statements>
return;
}
A method returning a String
public String String_Method()
{
String s = "its Ridiculous to do such kind of work, people here are just aim less";
return s;
}
A method returning an Int value
public int Int_Method()
{
int i = 5;
return(i);
}
I hope this will help you understand the use of return keyword, and as name suggest - The return keyword is always used with a method only to specify that the method is going to return something.

Why is that unreachable code?

I'm generating a question and answers of that randomly. And I want to generate new random arrays and answer options according to those when users chose the correct answer. But it says "unreachable code" when I add a boolean while loop... What is theproblem?
Thanks...
final boolean basadon = false;
while(basadon)
{
Random soru = new Random();
final int[] rastgele = new int[1];
for (int i=0; i<1; i++)
{
rastgele[i]= soru.nextInt(8);
}
ArrayList<Integer> cevap = new ArrayList<Integer>();
for (int k = 0; k <= 7; ++k)
{
cevap.add(k);
}
final Integer[] rastgele2 = new Integer[4];
if (rastgele[0]!=cevap.get(0))
{
rastgele2[0]=cevap.get(0);
}
else
{
rastgele2[0]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(1))
{
rastgele2[1]=cevap.get(1);
}
else
{
rastgele2[1]=cevap.get(3);
}
if (rastgele[0]!=cevap.get(2))
{
rastgele2[2]=cevap.get(2);
}
else
{
rastgele2[2]=cevap.get(3);
}
rastgele2[3]=rastgele[0];
Collections.shuffle(Arrays.asList(rastgele2));
view.setText(countries.get(rastgele[0]));
cevap1.setBackgroundResource(heads[rastgele2[0]]);
cevap1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele[0]==rastgele2[0])
{
cevap1.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap1.setBackgroundResource(heads[9]);
}
}
});
cevap2.setBackgroundResource(heads[rastgele2[1]]);
cevap2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[1]==rastgele[0])
{
cevap2.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap2.setBackgroundResource(heads[9]);
}
}
});
cevap3.setBackgroundResource(heads[rastgele2[2]]);
cevap3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[2]==rastgele[0])
{
cevap3.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap3.setBackgroundResource(heads[9]);
}
}
});
cevap4.setBackgroundResource(heads[rastgele2[3]]);
cevap4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (rastgele2[3]==rastgele[0])
{
cevap4.setBackgroundResource(heads[8]);
countries.remove(rastgele[0]);
basadon=true;
}
else {
cevap4.setBackgroundResource(heads[9]);
}
}
});
}
} }
Looks like you start with basedon value as false and later set it to true inside the loop.
So, Change
final boolean basedon = false
while (basedon) {
....
}
to
boolean basedon = false;
do {
....
} while (basedon);
while(basadon) is always false, so you never enter the loop. What you really mean is probably while(basadon==false). Also, don't declare basalon as final boolean because you want to modify its value later, and that will give error.
Why are you declaring all of those variables as final?
If bsadon for example needs to change from false to true, it can't be final. A final value is exactly that, a constant, it won't change.
Don't declare something as final unless you want it to keep the same value for the entire runtime of your program.
You are saying basadon is always "false", that's what final means, so the compiler is telling you you will never enter the while, since you need it to evaluate "true" to enter.
The expression between () in you while clause, needs to evaluate to true for the code to enter.
To your specific question which you have asked:
Why does the compiler give unreachable code warning
The answer is that since the condition in while loop is always false, there is no chance that the code in while loop will get executed. The warning is given to indicate that (given the current code situation) you have wasted your effort in typing that portion of code and it is guaranteed never to be executed. To rectify this, you can remove the final modifier from basedon and put a programming logic to set the value of basedon which will decide whether to enter the loop or not. If you want the loop to always run put while(true).
But I believe that what you wanted to ask was how to make the random question and answer generator. For that you'll have to post a bigger chunk of your code (It looks like you are trying to put a loop over a listener callback ?) and phrase your question to ask specific problems (possibly post a separate question).
It's probably complaining because basadon is known to be false and the body of the while loop cannot be reached. You can suppress the complaint by adding this annotation to the method:
#SuppressWarnings("unused")
You might also try removing the final modifier from the declaration of basadon. That might resolve the issue (but I'm not sure about that).
EDIT I finally noticed that you are trying to modify basadon directly from within your click listeners. That obviously won't work if basadon is final, yet you cannot access local variable unless it is final. I suggest you change basadon to be a (non-final) field of the enclosing class. Then all the warnings and errors should go away.

How to test for am or pm?

I am trying to test for am or pm in a if else statement..
if(am){
//Do something
else{
//Do something else
Ive tried
int am = cld.get(Calendar.AM_PM);
but the if else
wont take it as a parameter to test. Maybe because its not boolean.
How would i go about testing this?
You're correct that the if-else won't accept it because it is not boolean. Calendar.AM_PM only ever holds the value 0 or 1. A language like C would accept 0 or 1 as boolean; Java won't.
You want to do something more like this:
int am = cld.get(Calendar.AM_PM);
if (am == 0) {
// Do whatever for the AM
} else {
// Do whatever because it must be PM
}
Surely your if clause cannot accept integer as it is. You need something (comparison perhaps) to get boolean out of it.
if(am > 0)
{
//its PM
else { //its AM }
Calendar.AM_PM is an int. To evaluate it in an if statement, cast it to a boolean:
if((bool)am) {
//It's AM
} else {
//It's PM
}

Categories

Resources