Menu
CoddyTech

布尔条件

Coddy 面向 Java 开发者的 Dart 课程的第 7 课,共 48 课。

Java 和 Dart 都要求条件和短路逻辑运算符使用布尔值。Dart 的 bool 是不可为空的对象类型,除非将其标记为可空,这与 Java 的基本类型和包装类型之分不同。

条件和逻辑操作数必须是 bool。短路运算符的右侧只会在需要时运行,因此带有输出的回调可能完全不会执行。

完整的 Java 程序:

import java.util.*;
public class Example {
static boolean probe(){System.out.println("probe");return true;}
public static void main(String[] args){System.out.println(false&&probe()?"open":"closed");}
}

完整的 Dart 程序:

bool probe(){print('probe');return true;}
void main(){if(false && probe()){print('open');}else{print('closed');}}
challenge icon

挑战

简单

实现 safe(int temperature, bool doorClosed):当温度在 10 到 80 之间(含边界),且门处于关闭状态时,结果恰好为 true。输入是温度以及 true 或 false。返回小写的布尔值文本。

不要在可编辑文件中打印内容。提供的 exercise.dart 会解析输入并返回输出;锁定的驱动程序会独立测试公共 API,并在结果后打印一个换行符。

你的代码写在 functions.dart 和 exercise.dart 中。main.dart 包含提供的输入/输出代码,不能编辑。

亲手试试

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'functions.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
check(safe(40,true));check(!safe(40,false));
stdout.writeln(solve(input));
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Java 开发者的 Dart中的所有课

自己练习: Dart 在线编译器