[ create a new paste ] login | about

Link: http://codepad.org/Kcw9KTjx    [ raw code | fork ]

Dracorat - C++, pasted on Mar 1:
using System;
using System.Collections.Generic;
using System.Text;

namespace CreditCardValidation
{
	class Program
	{
		static void Main(string[] args)
		{
			char sAnother = 'y';
			do{
				Console.WriteLine("Enter a 16-digit credit card number:");
				string sCardNumber = Console.ReadLine();
				try
				{
					if(CardIsValid(sCardNumber))
					{
						Console.WriteLine("The card number checks out.");
					}
					else
					{
						Console.WriteLine("The card number is invalid. \r\nDouble check what was entered " + 
							"and if it's as shown on the card, call the police. \r\nASAP. \r\n\r\nLike now.");
					}
				}
				catch(ApplicationException)
				{
					Console.WriteLine("The card number you entered doesn't conform to card number standards.");
				}

				Console.WriteLine();
				Console.WriteLine("Another?");
				sAnother = Console.ReadKey(true).KeyChar;
				Console.Clear();
			}while(sAnother == 'y' || sAnother == 'Y');
		}

		private static bool CardIsValid(string sNumber)
		{
			string sTrimmedNumber = sNumber.Replace(" ", "").Replace("/", "").Replace(@"\", "").Replace("-", "");
			long LongNotUsed = 0L;
			if(sTrimmedNumber.Length != 16) throw new ImproperNumberOfDigitsException();
			if(long.TryParse(sTrimmedNumber, out LongNotUsed) == false)
				throw new CardNotNumericException();

			int iTally = 0;
			for(int i = 0 ; i < 16 ; i+=2) // can hard code 16 since it's the only valid length
			{
				int iDigit = sTrimmedNumber[i] - (int)'1' + 1;
				if(iDigit == 10) //0 is after 9 in ASCII so it comes out as 10
					iDigit = 0; //make it 0
				iDigit *= 2; //Double it
				//Add both parts
				iTally += iDigit % 10 + ((int) (iDigit / 10));
			}

			for(int i = 1 ; i < 16 ; i += 2) // these are the non-doubled digits
			{
				int iDigit = sTrimmedNumber[i] - (int) '1' + 1;
				if(iDigit == 10)
					iDigit = 0;
				iTally += iDigit;
			}

			if(iTally % 10 == 0)
				return true;
			return false;
		}
	}

	class ImproperNumberOfDigitsException : ApplicationException { }
	class CardNotNumericException : ApplicationException { }
}


Create a new paste based on this one


Comments: