dart 整数取反(从用户处获取输入并取反)

ddrv8njm  于 2022-12-06  发布在  其他
关注(0)|答案(1)|浏览(180)

我想建立一个程序,我想在整数多个输入和反向它..我怎么能做到这一点在 dart ?
我试过字符串但不知道整数

2fjabf4q

2fjabf4q1#

您可以执行以下操作:

import 'dart:io';

void main() {
  print('Input integers (q to stop):');
  final integers = <int>[];
  while (true) {
    // Reads input from the user.
    final input = stdin.readLineSync()!;

    // Check to see if the user is done inputting numbers.
    if (input == 'q') {
      break;
    }
    // Try to convert the String to an int. If input isn't a
    // valid integer, int.tryParse(input) == null.
    final integer = int.tryParse(input);
    if (integer != null) {
      integers.add(integer);
    }
  }
  print('Original order: $integers');
  // Reversing a List in Dart is simple: just call integers.reverse
  // to get an Iterable with the elements of integers in reversed order.
  // Calling integers.reverse.toList() will convert the Iterable to a List
  // so it's possible to print the entire list at once.
  print('Reversed order: ${integers.reversed.toList()}');
}

示例:

Input integers (q to stop):
1
2
3
r
4
5
q
Original order: [1, 2, 3, 4, 5]
Reversed order: [5, 4, 3, 2, 1]

相关问题