Skip to content

Instantly share code, notes, and snippets.

@liyuqian
Last active October 25, 2019 23:19
Show Gist options
  • Save liyuqian/0899a0327cae9aa792ec28ad21b6f795 to your computer and use it in GitHub Desktop.
Save liyuqian/0899a0327cae9aa792ec28ad21b6f795 to your computer and use it in GitHub Desktop.
import 'dart:math';
import 'dart:io';
import 'package:console/console.dart';
void main() {
Console.init();
double a = _askInputAndClearConsole('A, please tell me your value: ');
double b = _askInputAndClearConsole('B, please tell me your cost: ');
if (a < b) {
print('No deal.');
} else {
double p = b + (a - b) * Random().nextDouble();
print('Deal at price $p');
}
}
class _PrivacyConsole {
int _lineCount = 0;
void printLine(String line) {
print(line);
_lineCount += 1;
}
String readLine() {
String result = stdin.readLineSync();
_lineCount += 1;
return result;
}
void clear() {
for (int i = 0; i < _lineCount; i += 1) {
Console.moveCursorUp();
Console.eraseLine();
}
_lineCount = 0;
}
}
double _askInputAndClearConsole(String hint) {
double result = -1;
final _PrivacyConsole console = _PrivacyConsole();
try {
while (result == -1) {
console.printLine(hint);
String line = console.readLine();
result = double.tryParse(line);
if (result == null || result < 0 || result > 1) {
console.printLine('$line is not a valid input. Please input a fractional number between 0.00 and 1.00.');
result = -1;
}
}
console.printLine('The number you input is: $result.');
console.printLine('Enter y to confirm and clear the console.');
console.printLine('Enter anything else to stop and clear the console.');
String confirmation = console.readLine();
if (confirmation != 'y') {
throw Exception('Aborted by user input: $confirmation');
}
return result;
} catch (e) {
throw e;
} finally {
// make sure that nothing is leaked in all cases.
console.clear();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment