如何在 dart 中从控制台输入数据列表?
How to input a list of data from console in dart?
在 Dart 中,我想将用户 100 的数据输入到控制台的列表中。我该怎么做?
void main() {
int value;
List<int> list = [0];
var largest = list[0];
for (var i = 0; i < list.length; i++) {
list.add(stdin.readByteSync());
if (list[i] > largest) {
largest = list[i];
}
}
print(largest);
}
在聊天中进行了一些对话后,我们得出了以下解决方案:
import 'dart:io';
void main() {
// Create empty list
final list = <int>[];
// Number of numbers we want to take
const numbersWeWant = 100;
// Loop until we got all numbers
for (var i = 0; i < numbersWeWant; i++) {
int? input;
// This loop is for asking again if we get something we don't see as a number
do {
print('Input number nr. $i:');
// Get a number. input is going to be null if the input is not a number
input = int.tryParse(stdin.readLineSync() ?? '');
} while (input == null); // loop as long as we don't got a number
// Add the number we got to the list
list.add(input);
}
// Use list.reduce to find the biggest number in the list by reducing the
// list to a single value using the compare method.
print('Largest number: ${list.reduce((a, b) => a > b ? a : b)}');
}
在 Dart 中,我想将用户 100 的数据输入到控制台的列表中。我该怎么做?
void main() {
int value;
List<int> list = [0];
var largest = list[0];
for (var i = 0; i < list.length; i++) {
list.add(stdin.readByteSync());
if (list[i] > largest) {
largest = list[i];
}
}
print(largest);
}
在聊天中进行了一些对话后,我们得出了以下解决方案:
import 'dart:io';
void main() {
// Create empty list
final list = <int>[];
// Number of numbers we want to take
const numbersWeWant = 100;
// Loop until we got all numbers
for (var i = 0; i < numbersWeWant; i++) {
int? input;
// This loop is for asking again if we get something we don't see as a number
do {
print('Input number nr. $i:');
// Get a number. input is going to be null if the input is not a number
input = int.tryParse(stdin.readLineSync() ?? '');
} while (input == null); // loop as long as we don't got a number
// Add the number we got to the list
list.add(input);
}
// Use list.reduce to find the biggest number in the list by reducing the
// list to a single value using the compare method.
print('Largest number: ${list.reduce((a, b) => a > b ? a : b)}');
}