System Int 32帮助C#

时间:2015-02-28 15:27:13

标签: c#

我在visual studio 2010中编写了这段代码,当我编译它时,它给了我这个错误:

http://imgur.com/NyMgKtP

当我编译它时,它给了我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();
        }
    }
}

3 个答案:

答案 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。请考虑重构您的代码以符合此做法。
  • 在任何地方使用大括号 - 您的for循环不包含任何内容,而可能会导致意外结果。这是一项要求,而是一项建议。

您可以阅读有关数组here的更多信息。