I came across this problem and was confused when I got the answer wrong
String s = "dog";
switch( s )
{
case "dag" : System.out.print("7");
case "dog" : System.out.print("8");
case "dug" : System.out.print("9");
}
The answer comes out to 89 but I'm not sure why. I thought it was just 8. Thanks in advance for any help.
It happens because you don't break; after you've found a match, so it will continue to fall through. It's done in such a way so you can catch multiple things at once:
case 1:
case 2:
case 3:
// do something for 1-3
break;
With your code, you'd need
switch (s) {
case "dag":
System.out.print("7");
break;
case "dog":
System.out.print("8");
break;
case "dug":
System.out.print("9");
break;
}
You forgot to use break.
case "dog": //print
break;
Related
why the second switch code can run when t value not 30, program should return in the first swtich statement, it seems wild.
following is the code:
package main
import (
"fmt"
)
func main() {
fmt.Println("start...")
// change different t value to test
t := 10
switch t {
case 10:
case 20:
case 30:
fmt.Println("30...")
return
default:
fmt.Println("d...")
return
}
fmt.Println("does the following code run ?")
switch t {
case 10:
fmt.Println("10....")
case 20:
fmt.Println("20....")
}
fmt.Println("end...")
}
I've scoured the internet but it seems that I can't find documentation for the different types of Knex errors.
I would like to know these so I can implement proper error handling for my project. Where can I find this? They briefly mention the query error object here but no further depth is given. Am I missing something? It seems basic to me that they should have this well-documented.
What #Mikael said. It's a passthrough. For SQLite there are lists of DB errors here and here.
The db error code is included on the thrown exception object as the attribute .errno. I use this and the db driver documentation to be more verbose about the errors with the following function:
/**
* Gets Error strings using DB driver error number
* #param {number} errNo Database error number
* returns {object} errs: {"int":"Internal use string", "ext":"External usage string"};
*/
function getDBError(errNo) {
if (!errNo) {errNo = 0; };
let errs = {"int":null, "ext":null};
switch(errNo) {
case 2: errs.int="Internal logic error in SQLite"; break;
case 3: errs.int="Access permission denied"; break;
case 4: errs.int="Callback routine requested an abort"; break;
case 5: errs.int="The database file is locked"; break;
case 6: errs.int="A table in the database is locked"; break;
case 7: errs.int="A malloc() failed"; break;
case 8: errs.int="Attempt to write a readonly database"; break;
case 9: errs.int="Operation terminated by sqlite3_interrupt()"; break;
case 10: errs.int="Some kind of disk I/O error occurred"; break;
case 11: errs.int="The database disk image is malformed"; break;
case 12: errs.int="Unknown opcode in sqlite3_file_control()"; break;
case 13: errs.int="Insertion failed because database is full"; break;
case 14: errs.int="Unable to open the database file"; break;
case 15: errs.int="Database lock protocol error"; break;
case 16: errs.int="Database is empty"; break;
case 17: errs.int="The database schema changed"; break;
case 18: errs.int="String or BLOB exceeds size limit"; break;
case 19: errs.int="Abort due to constraint violation"; break;
case 20: errs.int="Data type mismatch"; break;
case 21: errs.int="Library used incorrectly"; break;
case 22: errs.int="Uses OS features not supported on host"; break;
case 23: errs.int="Authorization denied"; break;
case 24: errs.int="Auxiliary database format error"; break;
case 25: errs.int="2nd parameter to sqlite3_bind out of range"; break;
case 26: errs.int="File opened that is not a database file"; break;
case 27: errs.int="Notifications from sqlite3_log()"; break;
case 28: errs.int="Warnings from sqlite3_log()"; break;
case 100: errs.int="sqlite3_step() has another row ready"; break;
case 101: errs.int="sqlite3_step() has finished executing"; break;
case 301: errs.int="no such column"; break;
case 302: errs.int="no such table"; break;
case 303: errs.int="Cannot start a transaction within a transaction"; break;
default: errs.int="Database processing Error #"+errNo; break;
}
// errs.ext is future use to include end user messages and is currently ignored
if (!errs.ext) {errs.ext = errs.int; };
return errs;
};
There is no documentation of different errors thrown by knex. There are not that many places where knex actually creates Errors, usually its some other package where error is originated, except for some validations that feature is supported by the selected driver.
If a query fails, knex just passes the original error that was thrown by the database driver.
I am working on a breakout-type game using Cocos2dx.
I need to make a highscore table. After the game is finished, I'd like to display a page, where player types his username into text field.
I don't know how to add the user input into variable, so I can manipulate it later (mainly saving along with score to display it on the selected scene).
What is the simplest way of doing so?
Approach One:
If you just need to handle keyboard as key-event, It's as easy as these below lines of code:
HelloWorld::init()
{
...
auto keyboardListener = EventListenerKeyboard::create();
keyboardListener->onKeyPressed = [](EventKeyboard::KeyCode keyCode, Event* event)
{
switch (keyCode)
{
case EventKeyboard::KeyCode::KEY_UP_ARROW: /*Jump maybe*/ break;
case EventKeyboard::KeyCode::KEY_DOWN_ARROW: /*Crouch maybe*/ break;
case EventKeyboard::KeyCode::KEY_RIGHT_ARROW: /*Move Right maybe*/ break;
case EventKeyboard::KeyCode::KEY_LEFT_ARROW: /*Move Left maybe*/ break;
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(keyboardListener, this);
...
return true;
}
I think it's clear enough not to need any extra description.
Approach Two: if you need an input box that user/player can enter string with keyboard and you get what is entered, I recommend to use TextField which is available in cocos2d v3 ( and with some difficulty in v2) and has a full functionality. You can create and initial one of them as:
auto textField = cocos2d::ui::TextField::create("hint: enter here","Arial" , 30);
textField->setTextHorizontalAlignment(cocos2d::TextHAlignment::CENTER);
textField->setTextVerticalAlignment(cocos2d::TextVAlignment::CENTER);
textField->setColor(Color3B(100,100,100));
textField->setMaxLength(10);
textField->setMaxLengthEnabled(true);
textField->setTouchAreaEnabled(true);
textField->setTouchSize(Size(200,400));
textField->setPosition(...);
textField->addEventListener(CC_CALLBACK_2(HelloWorld::textFieldEvent, this));
this->addChild(textField, 10);
You can get entered data any time with std::string enteredData= textField->getString();
You can also do something when user entering text with two event as :
void HelloWorld::textFieldEvent(Ref *pSender, cocos2d::ui::TextField::EventType type)
{
switch (type)
{
case cocos2d::ui::TextField::EventType::ATTACH_WITH_IME:
{
textField->setColor(Color3B::BLACK);
// or whatever elese
break;
}
case cocos2d::ui::TextField::EventType::DETACH_WITH_IME:
{
textField->setColor(Color3B(100,100,100));
// or whatever elese
break;
}
}
}
Enjoy !
I am wanting to practice how I can stop the user to enter anything else other that a YES or NO and if so to loop back to the original instruction until the user will enter the correct data to continue. I wanted to see if this could be done with String, hopefully there is some good advice I could receive.
The code below is part of my original code, I did not want to paste the entire thing in here. This should be enough to get my point across what I'm trying to do, I'm new to programming and I want to learn.
type = JOptionPane.showInputDialog(UserName + ", Can You Multiply Both Your Numbers ?");
//Here is where I got stuck....
if (type.equals("Yes") || type.equals("yes")) {
StringResultFromUserOne = JOptionPane.showInputDialog("What is Your Awnser ?");
ResultFromUserOne = Integer.parseInt(StringResultFromUserOne);
if (ResultFromUserOne == AnswerForMult) {
System.out.println(ResultFromUserOne + " Is Correct.");
} else {
System.out.println(ResultFromUserOne + " Is Wrong, The Correct Answer Is: " + AnswerForMult);
}
} else {
System.out.println("The Answer Is: " + AnswerForMult);
}
What I think you want to do (I don't think I understand you correctly, please explain again if this isn't correct):
String type = JOptionPane.showInputDialog(UserName + ", Can You Multiply Both Your Numbers ?");
if (type.equalsIgnoreCase("yes")) {
// code if answer is yes.
} else if (type.equalsIgnoreCase("no")) {
// code if answer is no.
} else {
// code if answer isn't no or yes.
}
This is a simple code which checks what the input is and executes code depending on the answer.
I am having problems using strings in switch statements in Swift.
I have a dictionary called opts which is declared as <String, AnyObject>
I have this code:
switch opts["type"] {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
and on the lines case "abc" and case "def" I get the following error:
Type 'String' does not conform to protocol 'IntervalType'
Can someone explain to me what I am doing wrong?
This error is shown when an optional is used in a switch statement.
Simply unwrap the variable and everything should work.
switch opts["type"]! {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
Edit:
In case you don't want to do a forced unwrapping of the optional, you can use guard. Reference: Control Flow: Early Exit
According to Swift Language Reference:
The type Optional is an enumeration with two cases, None and Some(T), which are used to represent values that may or may not be present.
So under the hood an optional type looks like this:
enum Optional<T> {
case None
case Some(T)
}
This means that you can go without forced unwrapping:
switch opts["type"] {
case .Some("A"):
println("Type is A")
case .Some("B"):
println("Type is B")
case .None:
println("Type not found")
default:
println("Type is something else")
}
This may be safer, because the app won't crash if type were not found in opts dictionary.
Try using:
let str:String = opts["type"] as String
switch str {
case "abc":
println("Type is abc")
case "def":
println("Type is def")
default:
println("Type is something else")
}
I had this same error message inside prepareForSegue(), which I imagine is fairly common. The error message is somewhat opaque but the answers here got me on the right track. If anyone encounters this, you don't need any typecasting, just a conditional unwrap around the switch statement:-
if let segueID = segue.identifier {
switch segueID {
case "MySegueIdentifier":
// prepare for this segue
default:
break
}
}
Instead of the unsafe force unwrap.. I find it easier to test for the optional case:
switch opts["type"] {
case "abc"?:
println("Type is abc")
case "def"?:
println("Type is def")
default:
println("Type is something else")
}
(See added ? to the case)