我在visual studio 2010中编写了这段代码,当我编译它时,它给了我这个错误:
当我编译它时,它给了我System.Int32[]
而不是答案..任何建议?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
public class Result
{
private Random rn = new Random();
private int[] frequency=new int [7];
private int face;
public void rollDice()
{
Console.Write("Face\tFrequency\n");
for (int roll = 1; roll <= 6000; roll++)
{
face = rn.Next(1, 7);
}
switch (face)
{
case 1:
frequency[1]++;
break;
case 2:
frequency[2]++;
break;
case 3:
frequency[3]++;
break;
case 4:
frequency[4]++;
break;
case 5:
frequency[5]++;
break;
case 6:
frequency[6]++;
break;
}
}
public void display()
{
for (int i = 1; i < frequency.Length; i++)
Console.Write("{0} {1}\n", i, frequency);
Console.ReadKey();
}
public static void Main(string[] args)
{
Result rs = new Result();
rs.rollDice();
rs.display();
}
}
}
答案 0 :(得分:2)
替换
Console.Write("{0} {1}\n", i, frequency);
使用
Console.Write("{0} {1}\n", i, frequency[i]);
答案 1 :(得分:0)
public void display()
{
for (int i = 1; i < frequency.Length; i++)
Console.Write("{0} {1}\n", i, frequency[i]);
Console.ReadKey();
}
答案 2 :(得分:0)
数组是对象,这就是您的项目从父类ToString()
打印出Object
代码的原因。如果要打印出驻留在数组索引中的内容,则必须直接访问每个索引。您在switch-case
区块中设置索引时执行此操作,因此您在for-loop
中也会这样做:
for (int i = 1; i < frequency.Length; i++) {
Console.Write("{0} {1}\n", i, frequency[i]);//iterate through the indices
}
Console.ReadKey();
一些额外的要点可以为您提供更好的编码体验:
0
开始,而不是1
。请考虑重构您的代码以符合此做法。您可以阅读有关数组here的更多信息。