如何搜索和验证数组 [英] How to search and validate array

查看:86
本文介绍了如何搜索和验证数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作二十一点游戏,到目前为止,我已经完成了纸牌课程.卡类可以工作,但是我需要让我的Value set访问器搜索String [] values数组,然后确定value参数是否有效,如果不是,则抛出新的异常.我不确定如何执行此操作

任何帮助都将被申请

这是我的卡片课程的内容

I am creating a blackjack game and so far I have made a card class. The card class works but I need to have my Value set accessor search the String[]values array and then determine if the value argument is valid or not and if it isn''t then throw a new exception. I am not sure on how to do this

Any help would be appricated

Here is what I have for my card class

class Card
    {

        public enum SUIT { HEARTS, SPADES, DIAMONDS, CLUBS };

        private SUIT _suit;
        private String _value;

        public Card(SUIT suit, String value)
        {

            _suit = suit;
            _value = value;
        }
      
        public SUIT Suit
        {
            get
            {
                //Return member variable value
                return _suit;
            }
            set
            {
                _suit = value;
            }
        }

        private String[] values = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
        public String Value
        {
            get { return _value; }
            set
            {
                
                    _value = value;
                 
            }
        }
    }


这是我用来测试卡类的代码,X应该导致显示错误消息


Here''s my code I was using to test card class and X should cause the error message to be displayed

try
            {
                Card testCard1 = new Card(Card.SUIT.SPADES, "Q");
                Console.WriteLine(testCard1.Suit + " " + testCard1.Value);
                Card testCard2 = new Card(Card.SUIT.DIAMONDS, "10");
                Console.WriteLine(testCard2.Suit + " " + testCard2.Value);
                Card testCard3 = new Card(Card.SUIT.DIAMONDS, "X");
                Console.WriteLine(testCard3.Suit + " " + testCard3.Value);

            }
            catch (InvalidOperationException e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();

推荐答案

尝试这种方式:

Try this way:

private String[] values = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
public static String Value
{
    get { return _value; }
    set
    {
        if (!values.Contains(value))
        {
            throw new ArgumentException();
        }
        _value = value;

    }
}



异常和处理链接:
http://msdn.microsoft.com/en-us/library/ms173160% 28VS.80%29.aspx [ ^ ]

干杯!



Exceptions and handling link:
http://msdn.microsoft.com/en-us/library/ms173160%28VS.80%29.aspx[^]

Cheers!


尝试如下
if(!values.Contains(value))
    throw new ArgumentException("incorrect input"); 


这篇关于如何搜索和验证数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆