Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing Arguments To Main()

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi.Here is my question:
This program takes one command-line argument that specifies a person's name.It than searches through a two-dimensional array of strings for that name.If it finds a match,it displays that person's telephone number.This program is taken from a book.

public static int Main(string[] args)
{
string[,] numbers=
{
{"Tom","111"},
{"Mary","222"},
{"John","333"},
{"",""}
};
int i;

if(args.Length !=1)
{
Console.WriteLine("Not correct");
return 1;
}
else
{
for(i=0;numbers[i,0]!="";i++)
{
if(numbers[i,0]==args[0])
{
Console.WriteLine(numbers[i,1]);
break;
}
}
}
return 0;
}

If I write on a command-line as an argument one of the names that are also present in a string array or if I don't pass any arguments at all,than the program works fine.
But if I pass as an argument anything else,lets say 'Will' than I get 'INDEX-OUT-OF-RANGE-EXCEPTION'.Why is that?The loop should continue only untill numbers[i,0]!="" and than it should STOP.

Thank you for all your help!
 
Mine's a little different than yours, but not in anything that should functionally change it I don't think.

Take a look:

using System;

namespace ConsoleApplication1
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
string[,] numbers=
{
{&quot;Tom&quot;,&quot;111&quot;},
{&quot;Mary&quot;,&quot;222&quot;},
{&quot;John&quot;,&quot;333&quot;},
{&quot;&quot;,&quot;&quot;}
};
int i;

if(args.Length !=1)
{
Console.WriteLine(&quot;Not correct&quot;);
return;
}
else
{
for(i=0;numbers[i,0]!=&quot;&quot;;i++)
{
if(numbers[i,0]==args[0])
{
Console.WriteLine(numbers[i,1]);
return;
}
}
}
Console.WriteLine(&quot;Not correct&quot;);
}
}
} TealWren
 
Both versions work now.But I don't know why it didn't worked before,since you can see the code is OK.
Every once in a while when I open VS the settings are completely changed.Menus aren't in the place they were etc.
Could this be the reason?

Thank you for helping me!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top