Why is that unreachable code? - android

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.

Related

Android Questions App Answer==MyAnswer not null

I make android questions app. I can not find the right answer. Answer list.
Right answer: String answer = quizList.get(position).getAnswer();
Button Click:
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer =="A"){
lblsignboard.setText("Ok");
}
else
{
lblsignboard.setText("No");
}
}
});
Answer = "A", but this code does not work. Always gives the answer is no.
When you are comparing strings in java,always use .equals
Because the function (.equals) checks the actual contents of the string, the == operator checks whether the references to the objects are equal.
and now furthur using equalsignorecase you need not to worry about search string is in caps or small.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});
You can use this way too, to keep you code working even the answer key is of different case. Use either equals("A") or equalsIgnoreCase("a").
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (answer.equals("A") || equalsIgnoreCase("a")){
lblsignboard.setText("Ok");
}else{
lblsignboard.setText("No");
}
}
});
In Android we make use of two things to compare strings:
1. equals : this is used when you want to compare even case of the string.
2. equalsIgnoreCase: This is just for content comparison.
Here is the small illustration as how it works:
String myString = "heLLo";
if(myString.equals("hello"))
{
System.out.print("equals");
}
else if(myString.equalsIgnoreCase("hello"))
{
System.out.print("equalsIgnoreCase");
}
Here equalsIgnoreCase will be printed.
Strings can only compare by .equals method not by ==. Also you have to check string is null or not because .equals method may invoke
nullpointerexception and you app may crash.
buttonA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(answer!=null &&(answer.equals("A")||equalsIgnoreCase("a"))) {
lblsignboard.setText("Ok");
} else {
lblsignboard.setText("No");
}
}
});
String can compare is .equals or .eqalignorecase not a '==' sign.'==' using a int value compare.
String answer=item.get(position).getAnswer();
if(answer!=null && (answer.equals("A")||equalsIgnoreCase("a")){
Log.e("Comapare","----------Success");
}else{
Log.e("Comapare","----------not compare");
}

Random boolean generator for 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());
}

Build.Model doesn't provide the right information?

I am fairly new to the whole android-development.
I am trying to set a different layout depending on the Modelname.
I am working with the android-eclipse SDK
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
final String model = Build.MODEL;
if(model == "sdk")
{
setContentView(R.layout.activity_test_one);
} else
{
setContentView(R.layout.activity_test_two);
}
Toast.makeText(getApplicationContext(), model, Toast.LENGTH_SHORT).show();
}
The Toast says that the modelname is "sdk", but the if statement isn't executed, as indeed the else-part is executed.
What could be the reason for that?
You cannot use the '==' operator on the String as it checks to see if the string object is the same, not its content. Use .equals(String) instead.
if ("sdk".equals(model) {
...
}

App crashes when backspace key is pressed

I am trying to learn java while building an android app. I have a points calculator without a button it uses a textchange listener to calculate the total. When backspace key is pressed and the box has null it crashes. I tried validating using the code below (only validated on field to begin with). But it does not work. Any help would be greatly appreciated.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wwcalc);
etFat = (EditText)findViewById(R.id.editTextFat);
etFiber = (EditText)findViewById(R.id.editTextFiber);
etProtein = (EditText)findViewById(R.id.editTextProtein);
etCarbs = (EditText)findViewById(R.id.editTextCarbs);
tvTotal = (TextView)findViewById(R.id.textViewPoints);
TextWatcher watcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if(isEmpty(etFat) == false){
intFat = Integer.parseInt(etFat.getText().toString());
}
else{
etFat.setText("0");
etFat.hasFocus();
return;
}
intProtein = Integer.parseInt(etProtein.getText().toString());
intFiber = Integer.parseInt(etFiber.getText().toString());
intCarbs = Integer.parseInt(etCarbs.getText().toString());
calculate();
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
};
etFat.addTextChangedListener(watcher);
etProtein.addTextChangedListener(watcher);
etFiber.addTextChangedListener(watcher);
etCarbs.addTextChangedListener(watcher);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_wwcalc, menu);
return true;
}
public void calculate(){
//intTot = intFat + intCarbs + intFiber + intProtein;
intTot = (int) Math.ceil((intFat * (4/35)) + (intCarbs * (4/36.84)) - (intFiber* (4/50))+ (intProtein * (4/43.75)) ) ;
tvTotal.setText(Integer.toString(intTot));
}
private boolean isEmpty(EditText etText)
{
if(etText.getText().toString().trim().length() > 0 || etText.getText().toString().trim() != null)
return false;
else
return true;
}
}
Thanks for the help all. I got it working not sure if it is the best solution if anyone thinks there is a better way let me know. The try catch as suggested by conor catches the exception, then just insert a 0 set focus and select the 0
try {
intFat = Integer.parseInt(etFat.getText().toString());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
etFat.setText("0");
etFat.hasFocus();
etFat.selectAll();
}
Without seeing the stacktrace it is hard to know but i'm going to make a stab it anyway.
The following piece of your isEmpty() function is allowing false to be returned when the box could still be emtpy.
etText.getText().toString().trim() != null
This means that when you press backspace and clear the field it is empty but your function says it's not. Then the kicker, when your app thinks the field is not empty it tried to parse the contents for an integer value (which is not present). This attempt at parsing throws an exception and crashes your app.
I expect the stacktrace to show the app crashing at this line
intFat = Integer.parseInt(etFat.getText().toString());
It's worth noting that you should always surround calls like Integer.parseInt() with a try, catch block.
Hope that helps.
The exception should be caused by Integer.parseInt,
intFat = Integer.parseInt(etFat.getText().toString());
ntProtein = Integer.parseInt(etProtein.getText().toString());
intFiber = Integer.parseInt(etFiber.getText().toString());
intCarbs = Integer.parseInt(etCarbs.getText().toString());
If you pass string with spaces to parseInt, NumberFormatException will be thrown, you need to trim the text, and then set them, such as,
intFat = Integer.parseInt(etFat.getText().toString().trim());
try this
When backspace is pressed and a field is changed from say "0" to--> "" the operation that is supposed to convert the value to a double fails and crashed my application. "holder.mChoiceRNK"is the " EditView" reference " . If we look at what happens onAfterTextChanged we can set in a default value and then do a select all. The default value of "0" will not cause an error.
Cheers
And happy programming.
holder.mChoiceRNK.doAfterTextChanged {
Log.d(mTAG70, "130xxx 131 Pre Error")
if (holder.mChoiceRNK.text.toString() == "") {
holder.mChoiceRNK.setText("0") // new value if the backspace is pressed to create ""
holder.mChoiceRNK.selectAll()
} else{
Log.d(mTAG70, "130xxx 133 Past Error--> ${holder.mChoiceRNK.text}")
myRNKvotingArray[position].mRNK = holder.mChoiceRNK.text.toString().toDouble()
}}
Alternate solution:
holder.mChoiceRNK.doAfterTextChanged {
try {
myRNKvotingArray[position].mRNK =holder.mChoiceRNK.text.toString().toDouble()
} catch (err:Exception) {
holder.mChoiceRNK.setText("0")
holder.mChoiceRNK.selectAll()
}}

android unable to click button after return

I have a view to create an account. If the save button is clicked and any of the fields are left open, it displays a toast. If all fields are filled in, the account is saved. I tried to accomplish this with an onClickListener that has an iteration through all the fields. It works perfectly if a field is not filled in and it works perfectly if alle fields are filled, but when a field isn't filled, I type something in there, try to save again and the button doesn't do anything.
I think it has something to do with the return, but I don't know what to do else. If the return wouldn't be there, I would get a toast for each field that isn't filled in.
Here's the relevant code:
private void registerButtonListeners() {
mCRUDAccountButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1;
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
}
thanks guys!
You're never resetting your flag back to 0!
so...
#Override
public void onClick(View v) {
mEmptyField = 0;//RIGHT HERE (give them the benefit of the doubt)
for (int i = 0; i < mEditTexts.length; i++) {
if(mEditTexts[i].getText().length() == 0){
CommonCode.showToast(mNoTextTitles[i], mContext, mViewGroup);
mEmptyField = 1; //You were too optimistic, they failed.
return;
}
};
if (mEmptyField == 0){
saveState();
}
}
});
Now, you're doing this test for the first time, every time. Otherwise, you go through and set that flag to 1, and next time, even though your loop never finds a match, when you get to the if mPentyField == 0 test, it fails cause you set that to 1 in the previous go around.

Categories

Resources