我正在尝试学习编程,我编写了一个代码,用于将项目添加到ArrayList中。有许多for循环,每个循环都在特定的时间间隔内运行,这给了我正确的结果。 但是对于循环,我尝试了一个for循环使用IF Else语句,而这个doenots给了我正确的结果 请任何人检查并告诉我哪里出错了吗?
ArrayList dogs = new ArrayList();
ArrayList cats = new ArrayList();
ArrayList rabbits = new ArrayList();
ArrayList guineaPigs = new ArrayList();
ArrayList birds = new ArrayList();
ArrayList ferrets = new ArrayList();
//Before
for (int i = 0; i < 20; i++)
{
dogs.Add(new Animal(240.00, "D-PUP" + i));
}
for (int i = 0; i < 15; i++)
{
dogs.Add(new Animal(190.00, "D-JUN" + i));
}
for (int i = 0; i < 10; i++)
{
dogs.Add(new Animal(120.00, "D-ADU" + i));
}
for (int i = 0; i < 5; i++)
{
dogs.Add(new Animal(60.50, "D-SEN" + i));
}
//Before
for (int i = 0; i < 25; i++)
{
cats.Add(new Animal(220.00, "C-KIT" + i));
}
for (int i = 0; i < 30; i++)
{
cats.Add(new Animal(180.50, "C-JUN" + i));
}
for (int i = 0; i < 15; i++)
{
cats.Add(new Animal(120.00, "C-ADU" + i));
}
for (int i = 0; i < 10; i++)
{
cats.Add(new Animal(50, "C-SEN" + i));
}
//Before
for (int i = 0; i < 15; i++)
{
rabbits.Add(new Animal(120.75, "R-KIT" + i));
}
for (int i = 0; i < 15; i++)
{
rabbits.Add(new Animal(40.00, "R-ADU" + i));
}
//Before
for (int i = 0; i < 5; i++)
{
guineaPigs.Add(new Animal(15.00, "G-PUP" + i));
}
for (int i = 0; i < 10; i++)
{
guineaPigs.Add(new Animal(7.50, "G-ADU" + i));
}
//Before
for (int i = 0; i < 2; i++)
{
birds.Add(new Animal(90.00, "B-CHI" + i));
}
for (int i = 0; i < 5; i++)
{
birds.Add(new Animal(65.00, "B-ADU" + i));
}
//Before
for (int i = 0; i < 1; i++)
{
ferrets.Add(new Animal(150.00, "F-PUP" + i));
}
for (int i = 0; i < 3; i++)
{
ferrets.Add(new Animal(120.00, "F-ADU" + i));
}
for (int i = 0; i < 2; i++)
{
ferrets.Add(new Animal(30.50, "F-SEN" + i));
}
//After
int j = 30;
int i;
for(i = 0; i < j; i++)
{
if(i < 1)
{
ferrets.Add(new Animal(150.00, "F-PUP" + i));
}
if(i < 2)
{
birds.Add(new Animal(90.00, "B-CHI" + i));
ferrets.Add(new Animal(30.50, "F-SEN" + i));
}
if(i < 3)
{
ferrets.Add(new Animal(120.00, "F-ADU" + i));
}
if(i < 5)
{
dogs.Add(new Animal(60.50, "D-SEN" + i));
guineaPigs.Add(new Animal(15.00, "G-PUP" + i));
birds.Add(new Animal(65.00, "B-ADU" + i));
}
if(i < 10)
{
dogs.Add(new Animal(120.00, "D-ADU" + i));
cats.Add(new Animal(50, "C-SEN" + i));
guineaPigs.Add(new Animal(7.50, "G-ADU" + i));
}
if(i < 15)
{
dogs.Add(new Animal(190.00, "D-JUN" + i));
cats.Add(new Animal(120.00, "C-ADU" + i));
rabbits.Add(new Animal(120.75, "R-KIT" + i));
rabbits.Add(new Animal(40.00, "R-ADU" + i));
}
if(i < 20)
{
dogs.Add(new Animal(240.00, "D-PUP" + i));
}
if(i < 25)
{
cats.Add(new Animal(220.00, "C-KIT" + i));
}
if(i < 30)
{
cats.Add(new Animal(180.50, "C-JUN" + i));
}
}
答案 0 :(得分:1)
这不是编写代码的最佳方式,因为它令人困惑,而且正如您所看到的,使事情变得难以理解。理解你需要30只猫并且#34; C-JUN&#34;
真的很复杂使用单独的for
循环保留您的第一个选项,或者更改为dogs.AddRange(Enumerable.Range(0, 20).Select(i=>new Animal(240.00, "D-PUP" + i)))