'Can someone tell me why I am getting a 'null' output after execution?
Can someone tell me why I am getting a 'null' output at the end of Result-1?
#When I return just 'Exercise1() from the main, the null do not appear. #But I am confused and want to know what is causing this null in the result.
main.dart
import 'exercises/exercise1.dart';
void main() {
// return Exercise1();
print(Exercise1());
}
exercise1.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.");
}
Result-1: Run with print(Exercise1()) statement;
$ 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
Result-2: Run with return Exercise1() statement;
$ 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.
Solution 1:[1]
Since you did not declare the return type of Exercise1(), it's return type is dynamic.
Since you do not have a return statement in your method, the return type is void. Meaning it does not return anything.
Therefore, when you are printing out the return value of it's invocation, you are seeing null.
Solution 2:[2]
This is because Exercise1() is not "returning" anything. In other words, it's returning null value. If you want it to be "not null", you will have to return something in that function. Here's a fix. Lemme know if it works-
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.");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
