playerOneScore is a int, How can I pass it to use a label to display the score? This code just prints %i...
-(void)updateScoreLabels{
playerOneScoreLabel.text = #"%i",playerOneScore;
playerTwoScoreLabel.text = #"%i",playerTwoScore;
playerThreeScoreLabel.text = #"%i",playerThreeScore;
playerFourScoreLabel.text = #"%i",playerFourScore;
}
You need to initialize string using convenience constructor:
playerOneScoreLabel.text = [NSString stringWithFormat:#"%i",playerOneScore];
...
What you actually have in your code is comma operator - it evaluates its 1st parameter (that is assigns #"%i" string to a label), then evaluates and returns 2nd parameter - playerOneScore.
Related
Is there an easier approach to convert an Intellij IDEA environment variable into a list of Tuples?
My environment variable for Intellij is
GROCERY_LIST=[("egg", "dairy"),("chicken", "meat"),("apple", "fruit")]
The environment variable gets accessed into Kotlin file as String.
val g_list = System.getenv("GROCERY_LIST")
Ideally I'd like to iterate over g_list, first element being ("egg", "dairy") and so on.
And then ("egg", "dairy") is a tuple/pair
I have tried to split g_list by comma that's NOT inside quotes i.e
val splitted_list = g_list.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)".toRegex()).toTypedArray()
this gives me first element as [("egg", second element as "dairy")] and so on.
Also created a data class and tried to map the string into data class using jacksonObjectMapper following this link:
val mapper = jacksonObjectMapper()
val g_list = System.getenv("GROCERY_LIST")
val myList: List<Shopping> = mapper.readValue(g_list)
data class Shopping(val a: String, val b: String)
You can create a regular expression to match all strings in your environmental variable.
Regex::findAll()
Then loop through the strings while creating a list of Shopping objects.
// Raw data set.
val groceryList: String = "[(\"egg\", \"dairy\"),(\"chicken\", \"meat\"),(\"apple\", \"fruit\")]"
// Build regular expression.
val regex = Regex("\"([\\s\\S]+?)\"")
val matchResult = regex.findAll(groceryList)
val iterator = matchResult.iterator()
// Create a List of `Shopping` objects.
var first: String = "";
var second: String = "";
val shoppingList = mutableListOf<Shopping>()
var i = 0;
while (iterator.hasNext()) {
val value = iterator.next().value;
if (i % 2 == 0) {
first = value;
} else {
second = value;
shoppingList.add(Shopping(first, second))
first = ""
second = ""
}
i++
}
// Print Shopping List.
for (s in shoppingList) {
println(s)
}
// Output.
/*
Shopping(a="egg", b="dairy")
Shopping(a="chicken", b="meat")
Shopping(a="apple", b="fruit")
*/
data class Shopping(val a: String, val b: String)
Never a good idea to use regex to match parenthesis.
I would suggest a step-by-step approach:
You could first match the name and the value by
(\w+)=(.*)
There you get the name in group 1 and the value in group 2 without caring about any subsequent = characters that might appear in the value.
If you then want to split the value, I would get rid of start and end parenthesis first by matching by
(?<=\[\().*(?=\)\])
(or simply cut off the first and last two characters of the string, if it is always given it starts with [( and ends in )])
Then get the single list entries from splitting by
\),\(
(take care that the split operation also takes a regex, so you have to escape it)
And for each list entry you could split that simply by
,\s*
or, if you want the quote character to be removed, use a match with
\"(.*)\",\s*\"(.*)\"
where group 1 contains the key (left of equals sign) and group 2 the value (right of equals sign)
In a function i have this:
val sunRise = SunEquation(2459622)
binding.timeDisplay.setText("$sunRise.n")
The SunEquation-Class looks like this:
class SunEquation(var jDate: Int,) {
val jYear = 2451545
val ttOffset = .0008
var n = jDate - jYear + ttOffset
}
the button- text that appears is:
com.example.soluna.SunEquation#6d1a94b.n
i would expect a double-value
You have to add curly brackets around the value you want to inject into the String, like this:
binding.timeDisplay.setText("${sunRise.n}")
The shorthand syntax without brackets only works for a single variable, but not
for access to a nested field or other more complex expressions.
In your case, this results in the object itself being injected into the String, which is resembled by com.example.soluna.SunEquation#6d1a94b based on the result of the corresponding toString() call, which defaults to the class name and the reference id of the object. Followed by the literal String .n.
Alternatively, you could extract the value into a val beforehand and reference that.
val customN = sunRise.n
binding.timeDisplay.setText("$customN")
I have a object that I want to print it into string [key1=value1&key2=value2...etc] without the null value key value pair and comma into &.
So first of all i think of putting it into a map but it won't work and I don know how it work either.
val wxPayOrderObj = WxPayOrder(appid = "wx0b6dcsad20b379f1", mch_id =
"1508334851", nonce_str = UUID.randomUUID().toString(),sign = null,
body = "QQTopUp", out_trade_no = "20150806125346", total_fee = req.total_fee,
spbill_create_ip = "123.12.12.123",
trade_type = "JSAPI", openid = "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o")
so the output will be
appid=wx0b6dc78d20b379f1&mch_id=150788851&nonce_str=UUID.randomUUID().toString()&
body=QQTopUp&out_trade_no=20150806125346&total_fee=req.total_fee&
spbill_create_ip=123.12.12.123&trade_type=JSAPI&openid=oUpF8uMuAJO_M2pxb1Q9zNjWeS6o
anyone please help me, thanks in advances.
I don't really get your question, but you want to convert object to string (to a format that you want)?
Override the object's toString() to return "[key1=value1&key2=value2...etc]"
example
override fun toString(){
// make sure you compute the data first
val answer = "[key1=$value1&key2=$value2...etc]"
return answer
}
The $ is used in string templates (That's directly writing the name of a variable, the value will be used later to be concatenated) with other strings)
i have an enum.
Example:
enum events
{
MOVE_UP = 0,
MOVE_DOWN,
MOVE_RIGHT,
MOVE_LEFT,
};
i want to pass particular enum value as function arguments. for example:
my method definition is
(void) invokeEvents:(enum events)events withMessage:(NSDictionary*)message;
while calling this method i am passing arguments like:
[self invokeEvents:MOVE_UP|MOVE_DOWN|MOVE_RIGHT withMessage:message;
while checking the received parameter events is value is always last value of list of MOVE_UP|MOVE_DOWN|MOVE_RIGHT values. MOVE_RIGHT 2 as per enum value.
but i want all the values like "MOVE_UP|MOVE_DOWN|MOVE_RIGHT" equal 0, 1 and 2.
how can i pass the parameter so that i can get all values.
kindly give suggestion for my problem.
Thanks in advance.
Change your enum to:
{
MOVE_NONE = 0
MOVE_UP = 1<<0,
MOVE_DOWN = 1<<1,
MOVE_RIGHT = 1<<2,
MOVE_LEFT = 1<<3,
};
So you can pass parameters exactly as you want: MOVE_UP|MOVE_DOWN|MOVE_RIGHT.
And in invokeEvents:withMessage: check
if(events & MOVE_UP)
{
}
if(events & MOVE_DOWN)
{
}
...
.
If the title isn't clear; I want to be able to select any character from textbox without making some complex loops-dependent code (I can do that one). For example, let's consider this text is entered in a textbox:
hello user!
I want some syntax when I tell to get me the index 1's value, it gives me "h", for index 5 = "o"... etc
So, anyone knows what's the right syntax, please help!
string can be directly indexed without any special code.
//from metadata
public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
{
....
// Summary:
// Gets the character at a specified character position in the current System.String
// object.
//
// Parameters:
// index:
// A character position in the current string.
//
// Returns:
// A Unicode character.
//
// Exceptions:
// System.IndexOutOfRangeException:
// index is greater than or equal to the length of this object or less than
// zero.
public char this[int index] { get; }
....
}
dim str = "hello";
dim hchar = str(0);
dim echar = str(1);
dim lchar = str(2);
ect
Dim x As String = "Hello"
Console.Write(x.IndexOf("e")) 'Would return the position
Console.Write(x(x.IndexOf("e"))) 'Would return the character based upon the position
Console.Write(x(1)) 'Returns the character based at position 1 of the string
You can remove the Console.Write if you are using a WinForm.
TextBox1.Text = x(x.IndexOf("e"))
This should work.
Dim orig = "hello user!"
Dim res = Enumerable.Range(0,orig.Length).[Select](Function(i) orig.Substring(i,1))
So then you can do:
Dim x = res(0) 'x = "h"