Break out of switch statement execute one case - switch-statement

So basically, I am trying to get the switch statement to only execute one time. And not execute all of them.
Assume the player has all of the keys in their inventory.
I want only one case to execute and not go through all the cases.
(I'd like to only see one execute)
public int[] allKeys = {1543, 1544, 1545, 1546, 1547, 1548};
if (player.getInventory().containsAny(allKeys)) {
for (int id : allKeys) {
switch(id) {
case 1543:
System.out.println("executed");
break;
case 1544:
System.out.println("executed");
break;
case 1545:
System.out.println("executed");
break;
case 1546:
System.out.println("executed");
break;
case 1547:
System.out.println("executed");
break;
case 1548:
System.out.println("executed");
break;
default:
System.out.println("error!");
}
}
}

Your switch does only do "one at a time" - it is the fact your switch is in a for loop that is causing you problems...
You could put a "break" after the switch switch(x) { ... } break;, but really why loop when you don't want to - just switch on say the first key.

You are currently running the switch case inside the for loop that goes through every id's inside the array allKeys. Because you assumed the user to have allKeys, I would just remove the for loop, and pick whatever key you want the user to execute, and let that key go through the switch statement.

Related

Can we create semaphore for multiple conditions

I have a situation in my application where based on the different notifications I have to put a semaphore. Thing is that if I get type 1 notification, the semaphore should get by different portion of code.
Example:
void funcNotify(int notify)
{
switch(notify)
{
case type1:
Rtos_SemaphorePut(nitificationSemaphore, 1)
break;
case type2:
Rtos_SemaphorePut(nitificationSemaphore, 1)
break;
case type3:
Rtos_SemaphorePut(nitificationSemaphore, 1)
break;
default:
break;
}
}
So my question is can we create a semaphore which can be used for multiple notifications? And based on what type of notification I get, I will execute the required code for that.
The freeRTOS event_groups gave me the solution for this issue. I could set individual bits for each notification. Thanks.

MagicalRecord: how to cancel saveWithBlockAndWait?

I've got a service call which then saves a lot of data after returning:
[MagicalRecord saveWithBlockAndWait:^(NSManagedObjectContext *localContext) {
for (NSDictionary *dictionary in result) {
// create managed object, set parameters
}
}];
Now if the user logs out during this for-loop, I would like cancel the saving - how is this achieved?
You can't use saveWithBlockAndWait because it will still save even if you have code to exit the loop. Potentially you could reset the context before you exit, but you would need to carefully consider what side effects that could cause.
So, you want to run a block where you have control of the contents so you can check a flag while looping and exit the block without saving if the flag indicates a cancel.
Also, if you have so many items to save you should batch the save operation...
So, use MR_saveToPersistentStoreCompletion to save, but check a cancel flag first and return from the block if it's set:
localContext = NSManagedObjectContext.MR_contextForCurrentThread
[localContext performBlock:^{
for (int i...) {
...
if (i % 100 == 0) {
if (!cancelled) {
[context MR_saveToPersistentStoreAndWait];
} else {
return;
}
}
}
}];

What is the best way to implement a timer that will be stopped and restarted in a Java Swing Application?

Ok, I'm working on my final dilemna for my project. The project is an IPv4 endpoint updater for TunnelBroker's IPv6 tunnel. I have everything working, except for the timer. It works, however if the user disables the "automatic update" and reenables it, the application crashes. I need the timer to be on an thread outside of the EDT (in such a way that it can be destroyed and recreated when the user unchecks/checks the automatic update feature or changes the amount of time between updates).
What I'm pasting here is the code for the checkbox that handles automatic updates, and the timer class. Hopefully this will be enough to get an answer on how to do this (I'm thinking either it needs to be a worker, or use multi-threading--even though only one timer will be active).
private void jCheckBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
// TODO add your handling code here:
// if selected, then run timer for auto update
// set time textbox to setEditable(true) and get the time from it.
// else cancel timer. Try doing this on different
// class to prevent errors from happening on reselect.
int updateAutoTime = 0;
if (jCheckBox1.isSelected())
{
updateAutoTime = Integer.parseInt(jTextField4.getText())*60*1000;
if (updateAutoTime < 3600000)
{
updateAutoTime = 3600000;
jTextField4.setText(new Integer(updateAutoTime/60/1000).toString());
}
updateTimer.scheduleAtFixedRate(new TimerTask() {
public void run()
{
// Task here ...
if (jRadioButton1.isSelected())
{
newIPAddress = GetIP.getIPAddress();
}
else
{
newIPAddress = jTextField3.getText();
}
strUsername = jTextField1.getText();
jPasswordField1.selectAll();
strPassword = jPasswordField1.getSelectedText().toString();
strTunnelID = jTextField2.getText();
strIPAddress = newIPAddress;
if (!newIPAddress.equals(oldIPAddress))
{
//fire the tunnelbroker updater class
updateIP.setIPAddress(strUsername, strPassword, strTunnelID, strIPAddress);
oldIPAddress = newIPAddress;
jLabel8.setText(newIPAddress);
serverStatus = updateIP.getStatus().toString();
jLabel6.setText(serverStatus);
}
else
{
serverStatus = "No IP Update was needed.";
jLabel6.setText(serverStatus);
}
}
}, 0, updateAutoTime);
}
else
{
updateTimer.cancel();
System.out.println("Timer cancelled");
System.out.println("Purged {updateTimer.purge()} tasks.");
}
}
As I mentioned, this works once. But if the user deselects the checkbox, it won't work again. And the user can't change the value in jTextField4 after they select the checkbox.
So, what I'm looking for is this:
How to make this so that user can select and deselect the checkbox as they want (even if it's multiple times in a row).
How to make this so the user can change the value in jTextField4, and have it automatically cancel the current timer, and start a new one with the new value (I haven't done anything with the jTextField4 at all, so I'll have to create an event to cover it later).
Thanks, and have a great day:)
Patrick.
Perhaps this task would be better suited to a javax.swing.Timer. See Timer.restart() for details.
Note that Timer is relatively inaccurate over long time periods. One way to account for that is to have it repeat frequently but perform it's assigned task only one a certain time has been reached or passed.
Would I be able to wrap everything in the "task" portion of the call to Swing Timer, or do I have to create another class that handles the task?
You might want to wrap the grunt work in a SwingWorker to ensure the EDT is not blocked.
..I'm assuming that I would have to create the timer as a class-level declaration .. correct?
Yes, that is what I was thinking.

Why the command button is not being displayed in my emulator?

I have already added 5 cammands in a form and I want to add a sixth but It does not display the sixth?
I am posting my codes below.
public Command getOk_Lastjourney() {
if (Ok_Lastjourney == null) {
// write pre-init user code here
Ok_Lastjourney = new Command("Last Journey", Command.OK, 0);
// write post-init user code here
}
return Ok_Lastjourney;
}
public Form getFrm_planjourney() {
if (frm_planjourney == null) {
// write pre-init user code here
frm_planjourney = new Form("Plan journey", new Item[] { getTxt_From(), getTxt_To(), getCg_usertype(), getCg_userpref(), getCg_searchalgo() });
frm_planjourney.addCommand(getExt_planjourney());
frm_planjourney.addCommand(getOk_planjourney());
frm_planjourney.addCommand(getOk_planFare());
frm_planjourney.addCommand(getOk_planDistance());
frm_planjourney.addCommand(getOk_planTime());
frm_planjourney.addCommand(getOk_planRoute());
frm_planjourney.setCommandListener(this);
// write post-init user code here
System.out.println("Appending.....");
System.out.println("Append completed...");
System.out.println(frm_planjourney.size());
frm_planjourney.setItemStateListener(this);
}
return frm_planjourney;
}
Given System.out.println I assume you were debugging with emulator, right? in that case it would be really helpful to provide a screen shot showing how exactly does not display the sixth looks like.
Most likely you just got too many commands to fit to area allocated so that some of them are not shown until scrolled. There is also a chance that sixth command was reassigned to some other soft-button and you didn't notice that. Or there's something else - hard to tell with details you provided.
A general note - handling six actions with commands might be not the best choice in MIDP UI. For stuff like that, consider using lcdui List API instead. IMPLICIT kind of lists allow for more reliable and user friendly design than commands.

Views template theming

i have a template "views-view-field--tracker--name.tpl.php" for a view called tracker, and i am using an If...Else Statement in the template to print fields.
<?php
if ($node ->uid == 0) {
print $view->field['field_authorname_value']->render($row);
} else {
print $view->field['name']->render($row);
}
?>
The above code is not functioning as it should, its printing the first part nicely but not the second part. Though, printing without if statement seems to work ok. eg:
<?php
print $view->field['name']->render($row);
?>
Not sure whats wrong with the code, so looking for answers
I'm not sure exactly. What happens when you turn the if statement around?
<?php
if ($node ->uid != 0) {
print $view->field['name']->render($row);
} else {
print $view->field['field_authorname_value']->render($row);
}
?>
Or use a switch statement:
<?php
switch ($node ->uid) {
case 0:
print $view->field['field_authorname_value']->render($row);
break;
default:
print $view->field['name']->render($row);
}
?>
In drupal, an annoymous user == 0. However, you should probably check this first to ensure /what/ uid, your actually checking against. In other words, when you are debugging your page
insert
echo "uid is: ".$node ->uid;
/before/ the if statement, and that will let you know what you are checking against (i.e if it is always 0 or something other than 0 for non-annoymous users)
Hope that makes enough sense. Echoing values is your best friend when if else statements aren't working
[edit]
Also make sure you aren't an anonymous user, or else your code is working fine. Just a case of a human not working correctly (just did that yesterday as well)

Resources