I've been having difficulty replicating a piece of code that runs in Pascal into dart. The program asks for the scores of two teams to be entered, added and the totals displayed in the end. I managed to get all inputs and outputs, but the addition within the for loop outputs 0 or null. Any advice?
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double Totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i ) {
print('Enter team 1 player score');
double pscore1 = double.parse(stdin.readLineSync()!);
double Totscore1 = (Totscore1 pscore1);
}
print(' The total score is ${Totscore1}');
}
This is only for one score. Thanks in advance.
CodePudding user response:
You are declaring new variables in your for
loop instead of using the variables defined in your main()
method. Since your new variables is named the same, they will "shadow" your other variables since Dart's scoping rules means that when we refer to something, we start searching from current scope and then get up one level at a time until we hit global scope:
Instead, try do the following:
import "dart:io";
import "dart:math";
import "dart:convert";
void main() {
double pscore1 = 0;
double totscore1 = 0;
print('Enter enter team 1 name');
String? Team_one_Name = stdin.readLineSync();
print('Enter enter team 2 name');
String? Team_two_Name = stdin.readLineSync();
for (int i = 0; i < 5; i ) {
print('Enter team 1 player score');
pscore1 = double.parse(stdin.readLineSync()!);
totscore1 = totscore1 pscore1;
}
print(' The total score is ${totscore1}');
}
(I renamed your Totscore1
to totscore1
since variables should NEVER start with a cased letter in Dart if we follow the normal naming conventions)