error: Conditions must have a static type of 'bool' - flutter

I tried to make a calculator in flutter for the first time, but an error occur at the bool type that i don't understand. (on the "if" opertaion)
class _CalculatorAppState extends State<CalculatorApp> {
int? firstNum;
int? secondnum;
String? textToDisplay;
String? history = '';
String? res = '';
String? operation;
void btnOnClick(String btnVal){
print(btnVal);
if( btnVal == 'C'){
textToDisplay = '';
firstNum = 0;
secondnum = 0;
res= '';
} else if (btnVal == 'C'){
textToDisplay = '';
firstNum = 0;
secondnum = 0;
res= '';
history = '';
} else if ( btnVal == '+'||
btnVal == '-'||
btnVal == '/'||
btnVal == 'X') {
firstNum = int.parse(textToDisplay!);
res = '';
operation = btnVal;
} else if (btnVal == '='){
secondnum = int.parse(textToDisplay!);
if(operation = '+') {
res = (firstNum! + secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = '-') {
res = (firstNum! - secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = 'X') {
res = (firstNum! * secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
}
if(operation = '/') {
res = (firstNum! / secondnum!).toString();
history = firstNum.toString() + operation.toString() + secondnum.toString();
} else {
res = int.parse(textToDisplay! + btnVal).toString();
}
setState(() {
textToDisplay = res;
});
}
}
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:46)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:50)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:54)
error: Conditions must have a static type of 'bool'. (non_bool_condition at [calculator] lib\main.dart:58)

You're currently typing operation = 'x' which isnt valid syntax. You need a double '=', so:
if (operation == 'x') {
// do stuff
}

The equality operator is == not =.
At those lines listed you used = instead of ==.
And declare the variables as follows:
var firstNum = 0;
var secondnum = 0;
var textToDisplay = '';
var history = '';
var res = '';
var operation = '';

Related

make a function which calculate the number of same nearby character in flutter like aabcddaabb => 2abc2d2a2b

can anybody help me to build the function mentioned above I am using dart in the flutter and want this function
make a function which calculate the number of same nearby character in flutter like aabcddaabb => 2abc2d2a2b
Same
void main() {
var input = 'aabcddaabb';
print(getret(input));
}
String getret(String input) {
var ret = '';
var cc = '';
var co = 0;
cut(){
var c = input[0];
input = input.substring(1);
return c;
}
write(){
if(co == 1) ret = '$ret$cc';
if(co > 1) ret = '$ret$co$cc';
}
while(input.isNotEmpty){
final c = cut();
if(c != cc){
write();
cc = c;
co = 1;
}else{
co ++;
}
}
write();
return ret; // 2abc2d2a2b
}
There's probably a smarter and shorter way to do it, but here's a possible solution:
String string = 'aaabcddaabb';
String result = '';
String lastMatch = '';
int count = 0;
while (string.isNotEmpty) {
if (string[0] != lastMatch) {
result += '${count > 1 ? count : ''}$lastMatch';
lastMatch = string[0];
count = 0;
}
count++;
string = string.substring(1);
}
result += '${count > 1 ? count : ''}$lastMatch';
print(result); //3abc2d2a2b
I also came up with this smarter solution. Even though it's nice that it's a single expression it's maybe not very readable:
String string = 'aaabcddaabb';
String result = string.split('').fold<String>(
'',
(r, e) => r.isNotEmpty && e == r[r.length - 1]
? r.length > 1 &&
int.tryParse(r.substring(r.length - 2, r.length - 1)) != null
? '${r.substring(0, r.length - 2)}${int.parse(r.substring(r.length - 2, r.length - 1)) + 1}$e'
: '${r.substring(0, r.length - 1)}2$e'
: '$r$e');
print(result); //3abc2d2a2b

Flutter error: The body might complete normally

I'm trying to run this function in Flutter and I'm getting the error: The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type.
Try adding either a return or a throw statement at the end.
But if I add return ''; in the end it does not return any value, any solution?
String getWord() {
wordCounter += 1;
var rand = Random();
int wordLength = _words.length;
int randNumber = rand.nextInt(wordLength);
bool notUnique = true;
if (wordCounter - 1 == _words.length) {
notUnique = false;
return '';
}
while (notUnique) {
if (!_usedNumbers.contains(randNumber)) {
notUnique = false;
_usedNumbers.add(randNumber);
return _words[randNumber];
} else {
randNumber = rand.nextInt(wordLength);
}
}
}
The body might complete normally, causing 'null' to be returned, but the return type, 'String', is a potentially non-nullable type. Try adding either a return or a throw statement at the end. can be resolved like the below code.
Try to return only once at the end
String getWord() {
String returnString = "";
wordCounter += 1;
var rand = Random();
int wordLength = _words.length;
int randNumber = rand.nextInt(wordLength);
bool notUnique = true;
if (wordCounter - 1 == _words.length) {
notUnique = false;
}
while (notUnique) {
if (!_usedNumbers.contains(randNumber)) {
notUnique = false;
_usedNumbers.add(randNumber);
returnString = _words[randNumber];
} else {
randNumber = rand.nextInt(wordLength);
}
}
return returnString;
}

get_value of a feature in IFeatureCursor

I'm trying to read the attribute "POSTCODE" of the features in IFeatureCursor. The FID was successful read but the "POSTCODE" was failed. The runtime error 'An expected Field was not found or could not be retrieved properly. Appreciate your advise. Paul
private void test2(IFeatureCursor pFeatc1)
{
IFeature feature = null;
IFields pFields;
int ctcur = 0;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indxid = pFields.FindField("FID");
int indxpost = pFields.FindField("POSTCODE");
object valu = feature.get_Value(indxid);
string valupost = feature.get_Value(indxpost);
string aValu = Convert.ToString(valu);
Debug.WriteLine("FID: " + aValu + " Postcode: " + valupost);
ctcur++;
feature = pFeatc1.NextFeature();
}
MessageBox.Show("count cursor = " + ctcur);
}
I have modified the program and successfully read the feature attribute 'POSTCODE'. I have added IFeatureClass.Search(queryFilter, true) to search the feature again by FID and save in a cursor then use the 'feature.get_Value' to read the attribute. Please see my updated code below. Thanks.
private void test2(IFeatureCursor pFeatc1)
{
IMxDocument mxdoc = ArcMap.Application.Document as IMxDocument;
IMap map = mxdoc.FocusMap;
IFeatureLayer flayer;
IMaps pMaps = mxdoc.Maps;
for (int i = 0; i <= pMaps.Count - 1; i++)
{
map = pMaps.get_Item(i);
IEnumLayer pEnumLayer = map.get_Layers(null, true);
pEnumLayer.Reset();
ILayer pLayer = pEnumLayer.Next();
while (pLayer != null)
{
if (pLayer.Name == "AddrKey")
{
Debug.WriteLine("Layer: " + pLayer.Name);
flayer = (IFeatureLayer)pLayer;
IFeatureLayer pFeatureLayer = (IFeatureLayer)pLayer;
IFeatureClass pFeatureClass = pFeatureLayer.FeatureClass;
IFeature feature = null;
IFields pFields;
while ((feature = pFeatc1.NextFeature()) != null)
{
pFields = feature.Fields;
int indx = pFields.FindField("FID");
object valu = feature.get_Value(indx);
string sFID = Convert.ToString(valu);
IQueryFilter queryFilter = new QueryFilter();
queryFilter.WhereClause = ("FID = " + sFID);
Debug.WriteLine("FID: " + sFID);
queryFilter.SubFields = "POSTCODE";
int fieldPosition = pFeatureClass.FindField("POSTCODE");
IFeatureCursor featureCursor = pFeatureClass.Search(queryFilter, true);
while ((feature = featureCursor.NextFeature()) != null)
{
MessageBox.Show(feature.get_Value(fieldPosition));
}
feature = pFeatc1.NextFeature();
}
}
pLayer = pEnumLayer.Next();
}
}
}

VSCode language extension with hierarchical Outline, DocumentSymbol

I'm trying to get outline working with a custom language in VScode. I have the below code but I feel like it is slow because of the way I find a range in class. Are there better ways to find the range and assign children. I've thought about just keeping track of the depth of the brackets and assigning all functions/methods/classes in higher depths into the last item of previous depth.
It was based off of this answer.
class JSLDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
public provideDocumentSymbols(document: vscode.TextDocument,
token: vscode.CancellationToken): Thenable<vscode.DocumentSymbol[]> {
return new Promise((resolve, reject) => {
var symbols: vscode.DocumentSymbol[] = [];
var depth = 0;
for (var i = 0; i < document.lineCount; i++) {
var line = document.lineAt(i);
var txt = line.text;
var ltxt = txt.toLowerCase();
let open_brackets = ltxt.match(/\(/g) || [];
let close_brackets = ltxt.match(/\)/g) || [];
// console.log(ltxt)
// console.log(open_brackets, close_brackets)
//console.log(i, open_brackets.length, close_brackets.length)
depth += open_brackets.length - close_brackets.length;
//console.log(depth);
if (ltxt.includes("define class(")) {
let sname = txt.trim().substr(14, txt.trim().length - 16); //this is hard coded right now but it's kind of working
let detail = "ARGS:x, y returns z";
let start_pos = new vscode.Position(i, 0);
let n_bracket = 1;
let i_char = 0;
//let children: vscode.DocumentSymbol[] = []
let ds = new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Class, line.range, line.range);
for(var i_line = i; n_bracket > 0; i_line++){
let class_line = document.lineAt(i_line);
let mtxt = class_line.text;
let ic;
if(i == i_line) ic = 16;
else ic = 0;
for(i_char = ic; i_char < mtxt.length; i_char++){
if(mtxt[i_char] === "(") n_bracket++;
else if(mtxt[i_char] === ")") n_bracket--;
if(n_bracket === 0) break
}
if (/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i.test(mtxt)) {
let result = mtxt.match(/(\w[\w\d\s]*)=\s*method\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let mname = result[1].trim();
let m_details = ""
if(result.length == 3){
m_details = result[2].trim();
}
ds.children.push(new vscode.DocumentSymbol(mname, m_details, vscode.SymbolKind.Method, class_line.range, class_line.range));
}
if(n_bracket === 0) break
}
let end_pos = new vscode.Position(i_line, i_char);
let rng = new vscode.Range(start_pos, end_pos);
ds.range = rng;
//ds.children = children;
symbols.push(ds);
}
else if (/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/.test(ltxt)) {
let result = txt.match(/(\w[\w\d\s]*)=\s*function\({((?:\s*(?:\w[\w\d\s]*)(?:=[^,]*)?,?\s*)*)},/i)!;
let sname = result[1].trim();
let detail = "";
if(result.length == 3){
detail = "(" + result[2].trim() + ")";
}
symbols.push(new vscode.DocumentSymbol(sname, detail, vscode.SymbolKind.Function, line.range, line.range));
}
}
resolve(symbols);
});
}
}

Binary addition in java

I wrote a program for a binary addition in java. But the result is sometimes not right.
For example if i add 1110+111. The result should be 10101.
But my program throws out 10001.
Maybe one of you find the mistake.
import java.util.Scanner;
public class BinaryAdder {
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First: ");
String input1 = scan.next("(0|1)*");
System.out.print("Second: ");
String input2 = scan.next("(0|1)*");
scan.close();
System.out.println("Result: " + add(input1, input2));
}
}
this function is much simpler :
public static String binaryAdd(String binary1,String binary2){
return Long.toBinaryString(Long.parseLong(binary1,2)+Long.parseLong(binary2,2));
}
you can change Long.parseLong into Integer.parseInt if you don't expect very large numbers, you can also replace parse(Long/Int) with parseUnsigned(Long/Int) since you don't expect your strings to have a minus sign do you ?
You are not considering the case when
help1 + help2 = 3
So your method String add(String binary1, String binary2) should be like this:
public static String add(String binary1, String binary2) {
int a = binary1.length()-1;
int b = binary2.length()-1;
int sum = 0;
int carry = 0;
StringBuffer sb = new StringBuffer();
while (a >= 0 || b >= 0) {
int help1 = 0;
int help2 = 0;
if( a >=0){
help1 = binary1.charAt(a) == '0' ? 0 : 1;
a--;
} if( b >=0){
help2 = binary2.charAt(b) == '0' ? 0 : 1;
b--;
}
sum = help1 +help2 +carry;
if (sum == 3){
sb.append("1");
carry = 1;
}
else if(sum ==2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
}
if(carry == 1){
sb.append("1");
}
sb.reverse();
String s = sb.toString();
s = s.replaceFirst("^0*", "");
return s;
}
I hope this could help you!
sum = help1 +help2 +carry;
if(sum >=2){
sb.append("0");
carry = 1;
} else {
sb.append(String.valueOf(sum));
carry = 0;
}
If sum is 2 then append "0" and carry = 1
What about when the sum is 3, append "1" and carry = 1
Will never be 4 or greater
Know I'm a bit late but I've just done a similar task so to anyone in my position, here's how I tackled it...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
System.out.println("Enter the value you want to be converted");
Scanner inp = new Scanner(System.in);
int num = inp.nextInt();
String result = "";
while(num > 0) {
result = result + Math.floorMod(num, 2);
num = Math.round(num/2);
}
String flippedresult = "";
for(int i = 0; i < result.length(); i++) {
flippedresult = result.charAt(i) + flippedresult;
}
System.out.println(flippedresult);
}
}
This took an input and converted to binary. Once here, I used this program to add the numbers then convert back...
import java.util.Scanner;
public class Binary_Aids {
public static void main(String args[]) {
Scanner inp = new Scanner(System.in);
String decimalToBinaryString = new String();
System.out.println("First decimal number to be added");
int num1 = inp.nextInt();
String binary1 = decimalToBinaryString(num1);
System.out.println("Input decimal number 2");
int num2 = inp.nextInt();
String binary2 = decimalToBinaryString(num2);
int patternlength = Math.max[binary1.length[], binary2.length[]];
while(binary1.length() < patternlength) {
binary1 = "0" + binary2;
}
System.out.println(binary1);
System.out.println(binary2);
int carry = 0;
int frequency_of_one;
String result = "";
for(int i = patternlength -i; i >= 0; i--) {
frequency_of_one = carry;
if(binary1.charAt(i) == '1') {
frequency_of_one++;
}
if(binary2.charAt(i) == '1') {
frequency_of_one++;
}
switch(frequency_of_one) {
case 0 ;
carry = 0;
result = "1" + result;
break;
case 1 ;
carry = 0;
result = "1" + result;
break;
case 2;
carry = 1;
result = "0" + result;
breake;
case 3;
carry = 1;
result = "1" + result;
breake;
}
}
if(carry == 1) {
result = "1" + result;
}
System.out.println(result);
}
public static String decimalToBinaryString(int decimal1) {
String result = "";
while(decimal1 > 0) {
result = result + Math.floorMod(decimal1, 2);
decimal = Math.round(decimal1/2);
}
String flipresult = "";
for(int i = 0; i < result.length[]; i++) {
flipresult = result.charAt(i) + flippedresult;
}
return flippedresult;
}
}