Home > Software engineering >  how put the varibale x and y defined to make sum function because i only have this way for null safe
how put the varibale x and y defined to make sum function because i only have this way for null safe

Time:01-15

how i fix these problem and make x and y to can sum it ,because the vs code tell me the x and y does not Undefined name 'y' and Undefined name 'x'

import 'dart:io';

void main() {
  print('enter your first number ');
  var s = stdin.readLineSync();
//for null safety
  if (s != null) {
    int x = int.parse(s);
  }

  print('enter your second number');

  var a = stdin.readLineSync();

  if (a != null) {
    int y = int.parse(a);
  }
  print('the sum is');
//here can not see the x and y varibale how i can put it 
  int res = x   y;
  print(res);
}

CodePudding user response:

if (s != null) {
    int x = int.parse(s);
  }

Means here x is only available inside if statement.

Variables that are out of the scope to perform int res = x y;.

You can provide default value or use late

import 'dart:io';

void main() {
  print('enter your first number ');
  var s = stdin.readLineSync();
  late int x ,y; // I pefer providing default value x=0,y=0
//for null safety
  if (s != null) {
      x = int.parse(s);
  }

  print('enter your second number');

  var a = stdin.readLineSync();

  if (a != null) {
     y = int.parse(a);
  }
  print('the sum is');
 
  int res = x   y;
  print(res);
}

More about lexical-scope on dart.dev and on SO.

CodePudding user response:

In some cases, your variable might not get initialized with an int and it can be left as a null value, like in the if statement in your code (If the statement doesn't get triggered then the variables will be set as null). And dart with null safety ON doesn't allow that.

SOL: Initialize your variable with a default value or use the late keyword in front of them, while declaring.

var a=0;
var b=0;

OR

late var a;
late var b;
  •  Tags:  
  • Related