0
I want to generate a list of cars with random characteristics of make, model, color and year. These values are stored in a car list. The problem is, when it comes time to do the loop calling the function gerarCarro(), which adds random values to the car list, values from the third car start to be all the same.
using System;
using System.Collections.Generic;
using System.Linq;
public class MainClass
{
public static List<string> marcaLista = new List<string>();
public static List<string> modeloLista = new List<string>();
public static List<string> corLista = new List<string>();
public static List<string> carro = new List<string> ();
public static void Main(string[] args)
{
marcaLista.Add("Toyota");
marcaLista.Add("BMW");
marcaLista.Add("Volkswagen");
marcaLista.Add("GM");
marcaLista.Add("Mercedes");
modeloLista.Add("1.0");
modeloLista.Add("1.4");
modeloLista.Add("1.6");
modeloLista.Add("1.8");
modeloLista.Add("2.0");
corLista.Add("Branco");
corLista.Add("Prata");
corLista.Add("Preto");
corLista.Add("Cinza");
corLista.Add("Vermelho");
for (int i = 1; i <= 5; i++)
{
gerarCarro ();
foreach (string item in carro)
{
Console.WriteLine (item);
}
Console.WriteLine ();
carro.Clear ();
}
}
public static void gerarCarro ()
{
int randomizer;
Random random = new Random ();
for (int i = 0; i < 4; i++)
{
randomizer = random.Next (0, 5);
switch (i)
{
case 0:
carro.Add (marcaLista[randomizer]);
break;
case 1:
carro.Add (modeloLista[randomizer]);
break;
case 2:
carro.Add (corLista[randomizer]);
break;
case 3:
carro.Add (random.Next (2000, 2018).ToString());
break;
}
}
}
}
pf Creates a class for car rs
– Rovann Linhalis
This code is very confusing, it could be done in a much simpler way. I even had difficulty understanding the real problem, I have the impression that the solution is wrong because the problem is poorly defined.
– Maniero
The problem lies in the instantiation of
Randomwithin the methodgerarCarro(). Ignoring the rest of the code. How it is instantiated with the constructor without parameters picks up the sameseedfor the various instantiations, then generates the same pseudo random– Isac
I am still beginner in programming, so the code is confusing hahaha. What suggest to make it work properly? I didn’t understand how to actually fix it.
– Leo_gp