I'm new in Dart.
In the code bellow exception ccures :
void main(){
dynamic alpha = "String";
dynamic beta = 12;
print("Your code is so "+beta+" "+alpha);
}
Error :
type 'int' is not a subtype of type 'String'
Why when we use dynamic keyword to insist on telling the compiler for doing this job it's still got error? "combining string and other types"
When you declare your variable dynamic it does not mean the variable won't have a runtime type. It means the type can change:
dynamic alpha = 'String';
print(alpha.runtimeType); // prints String
alpha = 1;
print(alpha.runtimeType); // prints int
You can't do that with var. With var the compiler will infer the type, and it's fixed after that:
var beta = 'String';
print(beta.runtimeType);
beta = 1; // error: A value of type 'int' can't be assigned to a variable of type 'String'.
print(beta.runtimeType);
When you try to do "Your code is so " + beta you use the + operator of your String with an int paramter: beta.
You can see in the documentation that the + operator of String only accepts a String:
String operator +(String other);
If you wanted to use that operator you would have to convert the int variable to String:
print('Your code is so ' + beta.toString() + ' ' + alpha);
That's not remarkably beautiful. Instead of concatenation try string interpolation:
print('Your code is so $beta $alpha');
Related
I have a string coming from PC through serial to a microcontroller (Arduino), e.g.:
"HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
by this function I found:
String inputStringPC = "";
boolean stringCompletePC = false;
void serialEvent() {
while (Serial.available()) {
char inChar = (char)Serial.read();
inputStringPC += inChar;
if (inChar == '$') // end marker of the string
{
stringCompletePC = true;
}
}
}
I would like to extract the first number of it after the word HDD, CPU and also get the string after Weather (ie "cloudy"); my thinking is something like that:
int HDD = <function that does that>(Keyword HDD);
double CPU = <function that does that>(Keyword CPU);
char Weather[] = <function that does that>(Keyword Weather);
What is the right function to do that?
I looked into inputStringSerial.indexOf("HDD") but I am still a learner to properly understand what it does and don't know if theres a better function.
My approach yielded some syntax errors and confused me with the difference in usage between "String inputStringSerial" (class?) and "char inputStringSerial[]" (variable?). When I do 'string inputStringSerial = "";' PlatformIO complains that "string" is undefined. Any help to understand its usage here is greatly appreciated.
Thanks a bunch.
The String class provides member functions to search and copy the contents of the String. That class and all its member functions are documented in the Arduino Reference:
https://www.arduino.cc/reference/tr/language/variables/data-types/stringobject/
The other way a list of characters can be represented is a char array, confusingly also called a string or cstring. The functions to search and copy the contents of a char array are documented at
http://www.cplusplus.com/reference/cstring/
Here is a simple Sketch that copies and prints the value of the Weather field using a String object. Use this same pattern - with different head and terminator values - to copy the string values of the other fields.
Once you have the string values of HDD and CPU, you'll need to call functions to convert those string values into int and float values. See the String member functions toInt() and toFloat() at
https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/toint/
or the char array functions atoi() and atof() at
http://www.cplusplus.com/reference/cstdlib/atoi/?kw=atoi
String inputStringPC = "HDD: 55 - CPU: 12.6 - Weather: Cloudy [...] $";
const char headWeather[] = "Weather: "; // the prefix of the weather value
const char dashTerminator[] = " -"; // one possible suffix of a value
const char dollarTerminator[] = " $"; // the other possible suffix of a value
void setup() {
int firstIndex; // index into inputStringPC of the first char of the value
int lastIndex; // index just past the last character of the value
Serial.begin(9600);
// find the Weather field and copy its string value.
// Use similar code to copy the values of the other fields.
// NOTE: This code contains no error checking for unexpected input values.
firstIndex = inputStringPC.indexOf(headWeather);
firstIndex += strlen(headWeather); // firstIndex is now the index of the char just past the head.
lastIndex = inputStringPC.indexOf(dollarTerminator, firstIndex);
String value = inputStringPC.substring(firstIndex, lastIndex);
Serial.print("Weather value = '");
Serial.print(value);
Serial.println("'");
}
void loop() {
// put your main code here, to run repeatedly:
}
When run on an Arduio Uno, this Sketch produces:
Weather value = 'Cloudy [...]'
I was using this code to populate a cell in a spreadsheet using EPPlus:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
footerMonth1Cell.Value = monthsTruncatedYears[0];
footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
It was working fine, I thought, but a user complained that it was producing "green triangles" in the cells. "monthsTruncatedYears" is a generic list of string.
So I added this helper function:
public static void SetValueIntOrStr(this ExcelRangeBase range, object value)
{
string strVal = value.ToString();
if (!String.IsNullOrEmpty(strVal))
{
double dVal;
int iVal;
if (double.TryParse(strVal, out dVal))
range.Value = dVal;
else if (Int32.TryParse(strVal, out iVal))
range.Value = iVal;
else
range.Value = strVal;
}
else
range.Value = null;
}
...which I got from here, and then tried to refactor the original code to call that helper function like so:
using (var footerMonth1Cell = prodUsageWorksheet.Cells[columnFooterRow, MONTH1_COL])
{
footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
footerMonth1Cell.Style.Font.Size = DATA_FONT_SIZE;
footerMonth1Cell.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
However, it won't compile, telling me, "Cannot implicitly convert type 'void' to 'object'"
Since the second arg passed to SetValueIntOrStr(), namely "value", is of type object, I assume that is the problem. So why does the compiler apparently view monthsTruncatedYears[0] as being void? In the legacy code I assigned it as the value to the cell, and it wasn't void at that time, so...?!?
I tried casting the second arg to object like so:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueIntOrStr(footerMonth1Cell, object(monthsTruncatedYears[0]));
...but that won't compute, either, with "Invalid expression term 'object'"
...and this similar attempt:
footerMonth1Cell.Value = ReportRunnerConstsAndUtils.SetValueDoubleOrIntOrStr(footerMonth1Cell, monthsTruncatedYears[0] as object);
...elicits, "Cannot implicitly convert type 'void' to 'object'"
Note that the helper method is actually misnamed in the borrowed code; instead of "SetValueIntOrStr" it should be "SetValueDoubleOrIntOrStr"
The problem is the line
footerMonth1Cell.Value = SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
SetValueIntOrStr does not return any value (void) and therefore cannot be used to assign a value to the footerMonth1Cell.Value.
This would be valid code because the Value property is already changed inside the function:
SetValueIntOrStr(footerMonth1Cell, monthsTruncatedYears[0]);
Boxing Conversion can be acheived by using as keyword
So I tried to perform boxing using as keyword.
So I tried the below example
Eg 1:-
int i = 12;
string a = i.ToString(); // Boxing Conversion
Console.WriteLine(a); //This works
Console.ReadKey();
Eg 2:-
var aa = i as object; // This works
var a = (i as string) // Compile time error
var a = (i as string).ToString(); // Compile time error
Can anyone explain why boxing can't be performed using as keyword for a string reference type?
1)
int i = 12;
string a = i.ToString();
ToString() is not a boxing conversion at all (and I'm not sure the term is quite right - boxing is just boxing). It is conversion to string. "a" is totally different object, not related to i anymore. It's type is string and value is "12", not 12.
2)
int i = 12;
var aa = i as object;
It is boxing, but aa still keeps object of int type.
var a = (i as string)
Here you are trying to convert int to string, which is impossible to do what way.
What you are trying to do here is usual in many languages, like JavaScript. But C# has very strong rules about type conversions. And most of the time, you cannot just cast type to string and back.
I am trying to split a System::String at ":" using System::String::Split in my C++ code. The string to be split is called "responseString". It is a System::String. I have:
char id[] = { ':' };
return responseString->Split(id);
However, it errors at the "->" saying that no instance of the overloaded function matches the argument list. I checked the MSDN documentation, and see no information on doing this in C++.
I also tried the following, with the same results:
System::Char id[] = { ':' };
return responseString->Split(id);
In the documentation it shows the following example, but I do not know what to do with that:
array<String^>^ Split(
... array<wchar_t>^ separator
)
Any help would be appreciated!
Symbol delimiter can be either of type wchar_t, either String ^, as well as their array.
Here's a quick example:
String ^str="String:need:split;this";
array<wchar_t> ^id = { ':' ,';'};
array<String^> ^StringArray =str->Split(':');
array<String^> ^StringArray2 =str->Split(id);
for each(String^ temp in StringArray)
Console::WriteLine(temp);
Console::WriteLine();
for each(String^ temp in StringArray2)
Console::WriteLine(temp);
Using playground to simulate a problem with a core data based app turned up an issue I can't seem to understand.
class Pole {
var length: NSNumber!
}
var poles: [Pole] = []
let pole1 = Pole()
pole1.length = 1
poles.append(pole1)
let pole2 = Pole()
pole2.length = 2
poles.append(pole2)
var sum = poles.reduce(0) { $0 + $1.length } // error Could not find member 'length'
The property (attribute) named length is NSNumber as it is in a NSManagedObject class (entity).
Changing the Type from NSNumber! to Int! allows the line to compile and run correctly in playground.
Leaving the the Type as NSNumber! and changing the the offending line as follows:
var sum = poles.reduce(0) { $0 + Int($1.length) }
also compiles and run correctly in playground. The next step, taking this to the app, using actual NSManagedObject entity and attribute compiles but fails at runtime. The failure is 'unwrapping a nil'.
So bottom line I can't figure out how to use the reduce function when the attribute is a NSNumber and casting it to an Int doesn't seem to be acceptable.
NSNumber is a Foundation class that is used to wrap numbers that would otherwise be represented in a value type, so they can be used wherever a reference type is expected. Swift bridges integer literals to NSNumber, but not the other way around, so the original reduce closure was trying to add an integer literal to an NSNumber, getting confused, and giving you a weird error message.
Creating a new Int is one way to handle the problem:
var sum = poles.reduce(0) { $0 + Int($1.length) }
Or you can use NSNumber's integerValue property, which returns the instance's value as an Int:
var sum = poles.reduce(0) { $0 + $1.length.integerValue }