有人能告訴我為什么我在 Result-1 的末尾得到一個“空”輸出嗎?
#當我只從主回傳'Exercise1() 時,不會出現空值。#但我很困惑,想知道是什么導致結果中出現這個空值。
主要.dart
import 'exercises/exercise1.dart';
void main() {
// return Exercise1();
print(Exercise1());
}
練習1.dart
import 'dart:io';
Exercise1() {
stdout.write("What is your name? \n");
String? name = stdin.readLineSync();
stdout.write("Hi $name, What is your age? \n");
int? age = int.parse(stdin.readLineSync().toString());
int? yearsLeftFor100 = 100 - age;
print("Hello $name, your age is $age");
print("Hi $name, you will attain 100 years in another $yearsLeftFor100 years.");
}
結果 1:使用 print(Exercise1()) 陳述句運行;
$ dart run main.dart
What is your name?
John Doe
Hi John Doe, What is your age?
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.
null
結果 2:使用 return Exercise1() 陳述句運行;
$ dart run main.dart
What is your name?
John Doe
Hi John Doe, What is your age?
31
Hello John Doe, your age is 31
Hi John Doe, you will attain 100 years in another 69 years.
uj5u.com熱心網友回復:
由于您沒有宣告exercise1() 的回傳型別,它的回傳型別是動態的。
由于您的方法中沒有 return 陳述句,因此回傳型別為void。這意味著它不會回傳任何東西。
因此,當您列印出呼叫的回傳值時,您會看到null。
uj5u.com熱心網友回復:
這是因為 Exercise1() 沒有“回傳”任何東西。換句話說,它回傳空值。如果您希望它“不為空”,則必須在該函式中回傳某些內容。這是一個修復。讓我知道它是否有效-
String Exercise1() {
stdout.write("What is your name? \n");
String? name = stdin.readLineSync();
stdout.write("Hi $name, What is your age? \n");
int? age = int.parse(stdin.readLineSync().toString());
int? yearsLeftFor100 = 100 - age;
return("Hello $name, your age is $age \n Hi $name, you will attain 100 years in another $yearsLeftFor100 years.");
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/449852.html
上一篇:設計模式之命令模式
