Dart, lesson 3
So far your programs have printed fixed text. Real programs react to input. In this course, input arrives on standard input (stdin): the text you type, or text the tests feed in, one line at a time.
stdin lives in dart:io. Its readLineSync() method waits for one line and gives it
back as a string, without the line break at the end:
There is a catch. If there is no more input, readLineSync() returns null. That is why its
return type is String?, not String. Before you can call string methods on the result,
you must handle the missing case. Two common ways:
?? means "use the right side if the left side is null". The operator tells Dart to
trust you; if the value turns out to be null, the program stops with an error. For
exercises where the input format is guaranteed, is fine. When input might be missing,
prefer .
2 exercises to try what you just read.
!!??A line of input is always text, even if it looks like 42. Convert it before doing math:
int.parse throws an error on text like 'abc' or '4.5'. If you'd rather get null for
bad input, use int.tryParse. Stray spaces also break parsing, so .trim() the line first
when you're not sure it's clean.
Several numbers on one line? Split the line on spaces, then convert each piece:
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | add | 7 + 2 | 9 |
- | subtract | 7 - 2 | 5 |
* | multiply | 7 * 2 | 14 |
/ | divide (always a double) | 7 / 2 | 3.5 |
~/ | divide, keep whole part | 7 ~/ 2 | 3 |
% | remainder | 7 % 2 | 1 |
Two things surprise newcomers. First, / always produces a double, even for 6 / 3
(which is 2.0). Use ~/ when you want a whole number. Second, Dart's % never returns a
negative number for a positive divisor: -7 % 3 is 2, not -1.
Operators follow the usual math order: *, /, ~/ and % before + and -. Use
parentheses when in doubt.
Shortcuts update a variable in place: total += 5 means total = total + 5, and count++
adds one.
Friends share a restaurant bill in whole euros. Read the bill total on the first line and the number of friends on the second. Print how many whole euros each person pays, then how many euros are left over.
Input:
Output:
Read a temperature in Celsius (it may have decimals) and print it in Fahrenheit with exactly
one decimal place. The formula is F = C * 9 / 5 + 32.
Input:
Output:
import 'dart:io';
void main() {
final name = stdin.readLineSync();
print('Hello, $name!');
}final line = stdin.readLineSync() ?? ''; // use '' when input ran out
final sure = stdin.readLineSync()!; // "I promise it's there" (crashes if not)final age = int.parse(stdin.readLineSync()!);
final height = double.parse(stdin.readLineSync()!);final parts = stdin.readLineSync()!.trim().split(' ');
final a = int.parse(parts[0]);
final b = int.parse(parts[1]);100
3Each pays: 33
Left over: 121.570.7 F