Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

Dart: Accessing function from list

I want to have a new random number every time to print it, but it prints the same on. I tried so many thing, but I can't figure out what's wrong. Help me, please!

import 'dart:math';

int next_int() { return new Random().nextInt(100); }

void main()
{
  List<int> list = [next_int(), next_int(), next_int()];

  // expected new int each time but got the same one
  for (var i = 0; i < 3; i++)
  {
        List<int> cur_list = new List.from(list);
        print(cur_list[0]);
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This code will work as you expect:

import 'dart:math';

int next_int() { return new Random().nextInt(100); }

void main()
{
  List<int> list = [next_int(), next_int(), next_int()];

  // expected new int each time but got the same one
  for (var i = 0; i < 3; i++)
  {
        List<int> cur_list = new List.from(list);
        print(cur_list[i]); // <= Use the index value stored in "i" instead of 0
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...