Drag and Drop switch case, unreachable code? - java

Why is this code unreachable and how do I fix it?
public void draggingEvent() {
image15();
final int thisLetter = currentLetter;
mImageView15.getDrawable();
mImageView15 = (ImageView) findViewById(R.id.imageView15);
mImageView15.setOnDragListener(new OnDragListener() {
public boolean onDrag(View v, DragEvent de) {
// TODO Auto-generated method stub
final int action = de.getAction();
switch(action) {
case DragEvent.ACTION_DRAG_STARTED:
if (de.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
v.invalidate();
return (true);
}
break;
case DragEvent.ACTION_DRAG_ENTERED:
v.invalidate();
return (true);
break; //un reachable here
case DragEvent.ACTION_DRAG_LOCATION:
//ignore even for now
if (de.getX() == 250 && de.getY() == 195) {
mImageView17.setImageResource(thisLetter);
v.invalidate();
return (true);
}
if (de.getX() == 300 && de.getY() == 195) {
mImageView17.setImageResource(thisLetter);
return (true);
}
break;// here
case DragEvent.ACTION_DRAG_EXITED:
de.getResult();
break; //here
case DragEvent.ACTION_DROP:
ClipData.Item item = de.getClipData().getItemAt(thisLetter);
v.invalidate();
return (true);
break; // here
case DragEvent.ACTION_DRAG_ENDED:
v.invalidate();
if (de.getResult()) {
Log.e("it worked", "worked");
} else {
Log.e("failed", "sorry failed drag and drop");
return (true);
}
break; //here
default:
Log.e("Drag drop", "Failed to find area");
break; // and here
};
return false;
};
});

You cannot execute any Java statement after return:
return (true);
break; //un reachable here
just have return statement. (you have two such occurrences)

In general, statements after a return statement in Java will not be executed.
This is almost correct; there is an important exception which helps program stability, that being the finally block. For example
try {
doSomething();
return;
} finally {
cleanUp();
}
the function cleanUp() will be executed.

Because you do return (true) before your break the break will never be called.

Related

Switch while loop

I have a basic method that implements controlling of application menu using switch
public void applicationMenu(String input) {
switch (input) {
case "1":
findGroups();
break;
case "2":
findStudentsByCourseName();
break;
case "3":
addNewStudent();
break;
case "4":
deleteStudentById();
break;
case "5":
addStudentToCourse();
break;
case "6":
removeStudentCourse();
break;
default:
printDefault();
break;
}
}
I use this method with a while loop to call my application menu
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
String input = viewProvider.readString();
if (input.equals("7")) {
exit = true;
}
applicationMenu(input);
}
}
How can I trigger exit from switch case but keep the structure of two methods at the same time?
This should work:
public boolean applicationMenu(String input) {
boolean shouldContinue = true;
switch (input) {
case "1":
findGroups();
break;
case "2":
findStudentsByCourseName();
break;
case "3":
addNewStudent();
break;
case "4":
deleteStudentById();
break;
case "5":
addStudentToCourse();
break;
case "6":
removeStudentCourse();
break;
case "7":
shouldContinue = false;
break;
default:
printDefault();
break;
}
return shouldContinue;
}
...
public void callMenu() {
while (true) {
viewProvider.printMainMenu();
String input = viewProvider.readString();
if (!applicationMenu(input)) {
break;
}
}
}
As stated in comments, you could throw an Exception, but I typically don't like to do that if i'm not in an actual error state. It makes more sense to me to use a return value and evaluate the result to determine if the program should terminate:
public void callMenu() {
boolean exit = false;
while (!exit) {
viewProvider.printMainMenu();
exit = applicationMenu(viewProvider.readString());
}
}
public boolean applicationMenu(String input) {
switch (input) {
case "1":
findGroups();
return false;
case "2":
findStudentsByCourseName();
return false;
case "3":
addNewStudent();
return false;
case "4":
deleteStudentById();
return false;
case "5":
addStudentToCourse();
return false;
case "6":
removeStudentCourse();
return false;
case "7":
return true;
default:
printDefault();
}
return false;
}

Calling a method to return a different int from a switch

I'm trying to call a method and based on the input, return that value to a switch I have in another class. So if I were to choose the "1" element in my array, I would get reply returned as "4" back into my other class and make it run switch "4".
In the other class I have the switch "4" set to another method. However, I keep getting the int value "1" returned from my method as it keeps calling that method (switch "1"). Which makes sense since it's the "1" element in my array, it should then run switch "1", but I thought that by setting "reply = 4", it would return an int "4" into my other class and thus invoke switch "4".
How do I get my methods to return the value I want so I can put into my switch?
Here's my first class where I'm doing the calling:
package bunnyhunt;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class Messages {
//Objects
public Rooms roomCall = new Rooms();
//Instance Variables
public static boolean gameOver = false;
public static int roomNum;
public static int reply;
boolean visitedOtherRoom = false;
//Constructors
//Methods
public void start() {
//while loop
while (gameOver == false) {
//do-while loop
do {
String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Garden Gate"};
reply = JOptionPane.showOptionDialog(null, "You're at the Park Entrance! What do you want to do?", "Bunny Adventure", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]);
switch (reply) {
case 0:
System.out.println("oh man...Spring");
visitedOtherRoom = true;
roomCall.springMeadow();
break;
case 1:
System.out.println("oh man...Aeryn");
visitedOtherRoom = true;
roomCall.aerynsOverlook();
break;
case 2:
System.out.println("oh man...Garden");
visitedOtherRoom = true;
roomCall.gardenGate();
break;
default:
System.out.println("error");
}
} while (visitedOtherRoom == false);
switch (reply) {
case 0:
System.out.println("second 0!!!");
visitedOtherRoom = true;
roomCall.parkEntrance();
break;
case 1:
visitedOtherRoom = true;
System.out.println("yes man!");
roomCall.aerynsOverlook();
break;
case 2:
visitedOtherRoom = true;
roomCall.gardenGate();
break;
case 3:
visitedOtherRoom = true;
roomCall.peacefulPond();
break;
case 4:
visitedOtherRoom = true;
roomCall.readingNook();
break;
default:
System.out.println("default");
}
}
JOptionPane.showMessageDialog(null,
"Game Over!!!");
}
}
and my second where the things I call reside:
package bunnyhunt;
import javax.swing.JOptionPane;
public class Rooms {
public static int reply;
public int springMeadow() {
String[] springMeadow = {"Park Entrance", "Reading Nook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Spring Meadow! What do you want to do?", "Spring Meadow", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, springMeadow, springMeadow[0]);
switch (reply) {
case 0:
reply = 0;
break;
case 1:
reply = 4;
break;
case 2:
JOptionPane.showMessageDialog(null,
"You searched!");
break;
default:
System.out.println("error");
}
return reply;
}
public int aerynsOverlook() {
String[] aerynsOverlook = {"Park Entrance", "Peaceful Pond", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in Aeryn's Overlook! What do you want to do?", "Aeryn's Overlook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, aerynsOverlook, aerynsOverlook[0]);
return reply;
}
public int gardenGate() {
String[] gardenGate = {"Park Entrance", "Rose Gardent", "Butterfly Garden", "Flowering Forest"};
return reply;
}
public int readingNook() {
String[] readingNook = {"Spring Meadow", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Reading Nook! What do you want to do?", "Reading Nook", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, readingNook, readingNook[0]);
return reply;
}
public int parkEntrance() {
String[] parkEntrance = {"Spring Meadow", "Aeryn's Overlook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Park Entrance! What do you want to do?", "Park Entrance", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, parkEntrance, parkEntrance[0]);
return reply;
}
public int peacefulPond() {
String[] peacefulPond = {"Raven's Tower", "Aeryn's Overlook", "Search"};
Messages.reply = JOptionPane.showOptionDialog(null, "You're in the Peaceful Pond! What do you want to do?", "Peaceful Pond", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, peacefulPond, peacefulPond[0]);
return reply;
}
}
You are not returning a reply value from the start() method since this method is void AND switch statements inside don't return anything, despite they contain calls to appropriate methods like int aerynsOverlook(). You should modifystart` method like this:
public int start() {
...
switch (reply) {
case 0:
System.out.println("oh man...Spring");
visitedOtherRoom = true;
return roomCall.springMeadow();
...
Secondly, I don't see how you are calling start() method to get its return value and use it in the second switch. Your MEssages class doesn't have any connection with the Rooms

How to Handle Multiple drops for multiple components in drag and drop ;in one function or class?

I have 5 floating buttons and i have 5 drop listeners one for each.
i am looking a way to implement all those 5 listeners in one class or function.Please help me how to do this.And i want all the drop eworking fine when combined in one class
here is the sample:
imageView1.setOnDragListener(new View.OnDragListener()
{
#Override
public boolean onDrag(View v, DragEvent event)
{
switch (event.getAction())
{
case DragEvent.ACTION_DRAG_STARTED:
{
Log.e("DRaG1","START");
return true;
}
case DragEvent.ACTION_DRAG_ENDED:
{
Log.e("DRaG1","ENDED");
return true;
}
case DragEvent.ACTION_DRAG_ENTERED:
{
Log.e("DRaG1","ETER");
return true;
}
case DragEvent.ACTION_DRAG_EXITED:
{
Log.e("DRaG1","EXIT");
return true;
}
case DragEvent.ACTION_DROP:
{
Log.e("DRaG1","DROP");
return true;
}
}
return false;
}
});
imageView2.setOnDragListener(new View.OnDragListener()
{
#Override
public boolean onDrag(View v, DragEvent event)
{
switch (event.getAction())
{
case DragEvent.ACTION_DRAG_STARTED:
{
Log.e("DRaG2","START");
return true;
}
case DragEvent.ACTION_DRAG_ENDED:
{
Log.e("DRaG2","ENDED");
return true;
}
case DragEvent.ACTION_DRAG_ENTERED:
{
Log.e("DRaG2","ETER");
return true;
}
case DragEvent.ACTION_DRAG_EXITED:
{
Log.e("DRaG2","EXIT");
return true;
}
case DragEvent.ACTION_DROP:
{
Log.e("DRaG2","DROP");
return true;
}
}
return false;
}
});
i did it by myself code is here
In Main Activity do this:
imageView1.setOnDragListener(dragListener);
imageView2.setOnDragListener(dragListener);
make a class for Drag Listenrer and call it:
public class DragListener extends Activity implements View.OnDragListener {
#Override
public boolean onDrag(View v, DragEvent event)
{
final int action = event.getAction();
switch (action) {
case DragEvent.ACTION_DRAG_STARTED: {
Log.e("DRaG2", "START");
return true;
}
case DragEvent.ACTION_DRAG_ENDED: {
Log.e("DRaG2", "ENDED");
return true;
}
case DragEvent.ACTION_DRAG_ENTERED: {
Log.e("DRaG2", "ETER");
return true;
}
case DragEvent.ACTION_DRAG_EXITED: {
Log.e("DRaG2", "EXIT");
return true;
}
case DragEvent.ACTION_DROP: {
if (v.getId() == R.id.imageView1)
{
ClipData.Item item = event.getClipData().getItemAt(0);
Log.e("ITEM", item.getText().toString());
Log.e("DRaG2", String.valueOf(v.getId()));
}
else if (v.getId() == R.id.imageView2)
{
ClipData.Item item = event.getClipData().getItemAt(0);
Log.e("ITEM", item.getText().toString());
Log.e("DRaG2", String.valueOf(v.getId()));
}
else if (v.getId() == R.id.imageView3)
{
ClipData.Item item = event.getClipData().getItemAt(0);
Log.e("ITEM", item.getText().toString());
Log.e("DRaG2", String.valueOf(v.getId()));
}
return true;
}
}
return false;
}
}

android/java: stop a method from returning value until a part of the method is executed

Hi I have a boolean return type method in my android app. How ever in my method I am calling an api but my method immidately returns the first boolean value without waiting for the api callback part of the code.. how do i solve this? please take a look at the following code:
public boolean validateForm() {
flag=true;
//---- THIS CODE DOES NOT EXECUTE.. THE RETURN STATEMENT IS DIRECTLY EXECUTED---
checkSourceCode(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
validateCode = result;
if (!validateSourceCode(result)) {
flag = false;
}
if (flag) {
saveData();
}
}
});
//---- THE ABOVE CODE DOES NOT EXECUTE.. THE RETURN STATEMENT BELOW IS DIRECTLY EXECUTED
return flag; //This part is directly RETURNED without waiting for the above part of the code to execute
}
If i follow the answer given by Juan Felippo I have another issue to deal with then:
This is where I am calling the validateForm() method:
public boolean validate(int position) {
switch (position) {
case 0:
if (signUp_bgp_1.validateForm()) {
signUp_bgp_2.updateFields();
return true;
} else {
return false;
}
case 1:
signUp_bgp_2.validateForm(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
return result; // I GET ERROR HERE "CANNOT RETURN A VALUE FROM A VOID RETURN TYPE"
}
});
case 2:
return signUp_bgp_3.validateForm();
HERE IS MY COMPLETE CODE:
*I call validateForm method on case 1
public boolean validate(int position) {
switch (position) {
case 0:
if (signUp_bgp_1.validateForm()) {
signUp_bgp_2.updateFields();
return true;
} else {
return false;
}
case 1:
signUp_bgp_2.validateForm(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
bool =result; //CANNOT RETURN BOOLEAN HERE HOW TO HANDLE THIS?
}
});
case 2:
return signUp_bgp_3.validateForm();
case 3:
if (signUp_bgp_4.validateForm()) {
signUp_bgp_5.updateDetails();
return true;
} else {
return false;
}
case 4:
if (signUp_bgp_5.validateForm()) {
// signUp_bgp_5.updateDetails();
return true;
} else {
return false;
}
default:
return signUp_bgp_1.validateForm();
}
}
*My modified validateForm method according to Juan Fellipo's answer
public void validateForm(final BooleanCallBack mainCallback) {
flag=true;
checkSourceCode(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
validateCode = result;
if (!validateSourceCode(result)) {
flag = false;
}
if (!accept_checkbox.isChecked()) {
Toast.makeText(getActivity().getBaseContext(), "Accept The Terms & Conditions To Proceed", Toast.LENGTH_LONG).show();
// accept_checkbox.requestFocus();
flag = false;
}
if (!validateAddress()) {
flag = false;
}
if (!validateCountry()) {
flag = false;
}
if (!validatelandmark()) {
flag = false;
}
if (!validateDistrict()) {
flag = false;
}
// if (!validateCity()) {
// flag = false;
// }
// if (!validateMobilenumber()) {
// flag = false;
// }
if (!validatePincode()) {
flag = false;
}
if (!validateFullfillment()) {
flag = false;
}
if (flag) {
saveData();
}
mainCallback.onSuccess(flag);
}
});
}
The api method is asynchronous while your method is synchronous. You can provide a callback when response is ready.
Try:
public void validateForm(final BooleanCallBack mainCallback) {
flag=true;
checkSourceCode(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
validateCode = result;
if (!validateSourceCode(result)) {
flag = false;
}
if (flag) {
saveData();
}
mainCallback.onSuccess(flag)
}
});
}
and call the method:
someObject.validateForm(new BooleanCallBack() {
#Override
public void onSuccess(boolean result) {
//DO STH WITH RESULT
}
});
More info about sync/async and callbacks see :
What is a callback in java

How can I implement a string stack with a switch statement?

I would like to implement my StringStack in a switch statement how can i make this work in java. it sais i cant push() and argument with a char value. What is the best way around this for my validation method?
package xmlvalidator;
public class BasicXmlValidator implements XmlValidator {
#Override
public String[] validate(String xmlDocument) {
// TODO Auto-generated method stub
int charIndex = 0;
char currentCharacter;
String characterString;
while (charIndex < xmlDocument.length()) {
currentCharacter = xmlDocument.charAt(charIndex);
characterString = Character.toString(currentCharacter);
switch (currentCharacter) {
case '(': StringStack.push(currentCharacter);
break;
case '[': StringStack.push(currentCharacter);
break;
case '{': StringStack.push(currentCharacter);
break;
case ')': StringStack.push(currentCharacter);
break;
case ']': StringStack.push(currentCharacter);
break;
case '}': StringStack.push(currentCharacter);
break;
}
}
return null;
}
}
package xmlvalidator;
import static java.lang.System.*;
public class BasicStringStack implements StringStack {
public int count; // Number of Items in the array
public String[] stackItems; // The array that holds the stack items
public BasicStringStack(int initialSize) {
count = 0;
stackItems = new String[initialSize];
}
#Override
public void push(String item) {
// TODO Auto-generated method stub
if (count == stackItems.length) {
int newLength = (stackItems.length + 1);
String[] tempArray = new String[newLength];
arraycopy(stackItems, 0, tempArray, 0, stackItems.length);
stackItems = tempArray;
}
stackItems[count++] = item;
}
#Override
public String pop() {
if (count == 0) {
return null;
} else {
return stackItems[--count];
}
}
#Override
public String peek(int position) {
if ((position > count - 1) || (position < 0)) {
return null; // outside Bounds
} else {
return stackItems[count - position - 1];
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
}
You have the current char stored in a string using characterString = Character.toString(currentCharacter); just use it to push into stack.
StringStack.push(currentCharacter);
change to
StringStack.push(currentString);
Your problem is exactly as Java describes it to you. You pass a char to a method that expects String. The best fix would be
Stringstack.push(characterString);
Aside: because switch lets you fall through, you can rewrite it as
switch (currentCharacter) {
case '(':
case '[':
case '{':
case ')':
case ']':
case '}':
StringStack.push(characterString);
break;
}
Further aside: I did not address other potential problems in the code, but sought only to address the question asked.

Categories