Type int variable output error in Dart code

Asked

Viewed 160 times

0

I am starting in Dart code before going to the flutter, there is an error on the line var numero = int.parse(); which cannot insert an integer value, as I must enter an integer value correctly?

In case I wanted to make one output with type variable decimal how do I correctly capture this type of variable?

import 'dart:io';

main() {
  
  print ("Digite o seu nome: ");
  var nome = stdin.readLineSync();
  
  print ("Digite um número inteiro: ");
  var numero = int.parse(); // ERRO
  
  if (numero > 10) {
    print("${nome}, o número ${numero} é maior que 10.");
  } else if (numero < 10) {
    print("${nome}, o número ${numero} é menor que 10.");
  } else {
    print("${nome}, o número ${numero} é igual a 10.");
  }
}
  • If it is a value decimal, how should I make a output suitable for this type of variable?

1 answer

1


According to the documentation, the method int.parse must receive a string in its first argument.

However, you are not passing any value to the parse can work (which causes the error). To correct, you should ask (also using the stdin.readLineSync) the user age and pass as argument. So:

import 'dart:io';

main() {
  
  print("Digite o seu nome: ");
  var nome = stdin.readLineSync();
  
  print("Digite um número inteiro: ");
  var numeroStr = stdin.readLineSync();
  var numero = int.parse(numeroStr); // numero é int
  
  if (numero > 10) {
    print("${nome}, o número ${numero} é maior que 10.");
  } else if (numero < 10) {
    print("${nome}, o número ${numero} é menor que 10.");
  } else {
    print("${nome}, o número ${numero} é igual a 10.");
  }
}

See working on Repl.it.

You can also reduce the two lines to one. So:

var numero = int.parse(stdin.readLineSync());

Remember that if the user passes a non-numeric value, an exception will be thrown.

If you want to do the parse of a double (number with "decimal part"), you can use the method double.parse:

var numero = double.parse(stdin.readLineSync());

By your question, you seem to be confusing double with decimal. Be careful because float, double and decimal are different things.

  • If it is a variable of type decimal how it would be decimal.parse(numeroStr)?

  • Digite o seu nome: &#xA;Uncaught Error: Unsupported operation: StdIOUtils._getStdioInputStream

  • In this case you look for the method double.parse. Be careful not to confuse decimal with float or double. They have different meanings... Natively, Dart doesn’t have a decimal type.

  • How do I make the value to be typed in the same line as the print? To stay Digite o seu nome: Kyukay.

  • @Kyukay, it would be ideal if you opened another question for this. : ) But use stdout.write instead of print, since the latter adds a \n at the end of the string passed. Already o stdout.write, nay.

  • worked out, vlw.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.