我如何解決這些問題并使 x 和 y 可以求和,因為 vs 代碼告訴我 x 和 y 沒有未定義名稱“y”和未定義名稱“x”
import 'dart:io';
void main() {
print('enter your first number ');
var s = stdin.readLineSync();
//for null safety
if (s != null) {
int x = int.parse(s);
}
print('enter your second number');
var a = stdin.readLineSync();
if (a != null) {
int y = int.parse(a);
}
print('the sum is');
//here can not see the x and y varibale how i can put it
int res = x y;
print(res);
}
uj5u.com熱心網友回復:
if (s != null) {
int x = int.parse(s);
}
這里的意思x是只在內部if宣告中可用。
超出執行范圍的變數int res = x y;。
您可以提供默認值或延遲使用
import 'dart:io';
void main() {
print('enter your first number ');
var s = stdin.readLineSync();
late int x ,y; // I pefer providing default value x=0,y=0
//for null safety
if (s != null) {
x = int.parse(s);
}
print('enter your second number');
var a = stdin.readLineSync();
if (a != null) {
y = int.parse(a);
}
print('the sum is');
int res = x y;
print(res);
}
有關dart.dev和SO上的詞法范圍的更多資訊 。
uj5u.com熱心網友回復:
在某些情況下,您的變數可能不會使用 int 進行初始化,它可以保留為空值,就像代碼中的 if 陳述句一樣(如果該陳述句沒有被觸發,那么變數將被設定為空)。并且 null 安全 ON 的飛鏢不允許這樣做。
SOL:用默認值初始化你的變數,或者在宣告時在它們前面使用late關鍵字。
var a=0;
var b=0;
或者
late var a;
late var b;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/411099.html
標籤:
上一篇:未找到Androidsdkmanager。更新到最新的AndroidSDK并確保已安裝cmdline-tools以解決此問題
