Reputation: 719
Here is an assignment from a class that I was never able to complete.
I make a constructor and try to call the method. It never works. I really don't know what I am doing wrong here. I ask for an input and readline, then type my constructor, but it won't call. How am I supposed to call this?
public static int RomToNum(String rom)
{
StringBuilder temp = new StringBuilder();
int ret = 0;
char[] letters = rom.ToArray();
foreach (char item in letters)
{
if (item == 'M')
ret += 1000;
if (item == 'D')
ret += 500;
if (item == 'C')
ret += 100;
if (item == 'L')
ret += 50;
if (item == 'X')
ret += 10;
}
for (int x = 0; x < letters.Length; x++)
{
if (letters[x] == 'I' && !letters.Contains('V'))
{
ret += 1;
}
else
{
if (letters[x] == 'I' && x != letters.Length-1)
{
ret += 4;
break;
}
else if (letters[x] == 'I' && x == letters.Length-1)
{
ret += 6;
break;
}
}
}
return ret;
}
Upvotes: 0
Views: 974
Reputation: 2372
I honestly don't know why you want to call the method with a constructor rather than what Precious1tj posted. But If you want to use the constructor to call the method you can do this:
class Program
{
static void Main(string[] args)
{
Class2 c2 = new Class2("X"); //outputs '10' once it's instantiated
Console.ReadKey();
}
}
class Class2
{
//overloaded ctor
public Class2(string rom)
{
Console.WriteLine(RomToNum(rom));
}
public static int RomToNum(String rom)
{
StringBuilder temp = new StringBuilder();
int ret = 0;
char[] letters = rom.ToArray();
foreach (char item in letters)
{
if (item == 'M')
ret += 1000;
if (item == 'D')
ret += 500;
if (item == 'C')
ret += 100;
if (item == 'L')
ret += 50;
if (item == 'X')
ret += 10;
}
for (int x = 0; x < letters.Length; x++)
{
if (letters[x] == 'I' && !letters.Contains('V'))
{
ret += 1;
}
else
{
if (letters[x] == 'I' && x != letters.Length - 1)
{
ret += 4;
break;
}
else if (letters[x] == 'I' && x == letters.Length - 1)
{
ret += 6;
break;
}
}
}
return ret;
}
}
The downside of calling the method from the constructor is that you'll have to create a new object of the class whenever you want to evaluate a new Roman Numeral.
Upvotes: 0
Reputation:
Since you're calling it in another class
you use
CurrentClass.RomToNum("String Values");
You dont need to create an object for the class in order to reference this method because it is a static method
Upvotes: 1