Click here to Skip to main content
15,879,095 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to create a program which takes user input and based on that provides some results.

Input is in the form of a sting variable and it is checked across strings stored in an array .
If the input is matches these stored variables then a success message is displayed or else error message is displayed.

The problem is, when the input matches to the value stored in array along with some other letter as an input, even then it accepts it and show the Success message.

Any suggestion on how to do it more efficiently and improve the code ?

C#
using System;
namespace LearnigToProgram{
	class Travel{
		

		string []travellers_name=new string[8];
		public string []departure_location=new string[4];
		public string[]arrival_location=new string[4];
		int[]mobileno=new int[8];

		public Travel(){

			departure_location[0]="Phuket";
			departure_location[1]="Amsterdam";
			departure_location[2]="Mumbai";
			departure_location[3]="Thailand";

			arrival_location[0]="1.Bangkok";
			arrival_location[1]="2.Damascas";
			arrival_location[2]="3.Sri Lanka";
			arrival_location[3]="4.Peshawar";
		}
	}

	class TripManager{
		static void Main(){

			int casecheck1,casecheck2,casecheck3,casecheck4;
			string welcome_msg="Welcome to Sharp Travel Planner .\nPlease select your dream destination\n";
			Travel display_location = new Travel ();
			Console.WriteLine (welcome_msg);
			for (int i = 0; i < display_location.departure_location.Length; i++)
				Console.WriteLine (display_location.arrival_location [i]);

			string input=Console.ReadLine ();
			casecheck1 = input.IndexOf ("Bangkok", StringComparison.Ordinal);
			casecheck2 = input.IndexOf ("Damascas", StringComparison.Ordinal);
			casecheck3 = input.IndexOf ("Sri Lanka", StringComparison.Ordinal);
			casecheck4 = input.IndexOf ("Peshawar", StringComparison.Ordinal);
			if((casecheck1==0)|(casecheck2==0)|(casecheck3==0)|(casecheck4==0))
				Console.WriteLine ("Your choice is {0}", input);
			//if (input != ("Bangkok") || ("Damascas") || ("Sri Lanka") || ("Peshawar"))
			else	
			Console.WriteLine ("Destination not available");


		}


	}

}
Posted
Updated 10-Sep-16 9:52am
v3
Comments
[no name] 10-Sep-16 14:14pm    
The Contains method would help you.

Here's an example of how you might validate input:
C#
string input=Console.ReadLine ();

if (input == "") Environment.Exit(-1); // handle user entered nothing ?
                             
input = input.Trim().ToLower(); // get rid of white-space, make all lower-case

string destination = "";

foreach(string dest in display_location.arrival_location)
{
    if(dest.ToLower().Contains(input))
    {
        destination = dest;
        break;
    }
}

if (destination == "") Environment.Exit(-1); // handle no match

// do something with valid entry ?
switch(input)
{
        case "Bangkok":
            // ?
            break;

        case "Damascas":
            // ?
            break;

        // left for you to  complete

        default:
            break;
}
Notes:

1. by converting the user input to lower-case and comparing it with the destination names in lower-case, the user can have a bit more leeway to make typing mistakes in terms of case.

2. the code to exit the Console app you see here are just place-holders.

The real work in a Console app, imho, is to get a loop structure set-up so you can let the user repeat data-entry ... until they either "succeed," or they enter some character that causes the Console to terminate.
 
Share this answer
 
A more general solution would be to treat your list of destinations rather like a database and search for the entered text. If you do this then you can extend the list of destinations without having to hard code your test. As a general rule hard coding is a bad thingTM and it can lead to all sorts of unpleasantness including but not limited to code that is fragile and difficult to maintain.

So assuming that the list of destinations is in scope you could do something like the following :

C#
string foundDestination = "";
for (int i=0; i < arrival_location.length; i++) {
  // We'll use indexof but other comparison methods are available.
  // Have a look at String.Equals(...) to start with.
  // There are ways of exiting the loop early when a match is made. 
  // Further reading for you.
  if (arrival_location[i].IndexOf(input, Ordinal) >= 0 ) {
    foundDestination = input;
  }
}

if (foundDestination.length == 0) {
 // Tell the user no match.
} else {
 // Display all matches made.
 // 
} 


If you want to get fancy then there are other ways of searching through data for example...

C#
// Xamarin docs say linq is supported, but I don't know how well.
Using System.Linq;

// We'll use indexof but other comparison methods are available.
// Have a look at String.Equals(...) to start with.
IEnumerable<string> findLocation = From string dest in arrival_location
                                   where dest.indexof(input, Ordinal) >=0
                                   select dest;

// We allow for the possibility of multiple matches
string[] matches = findLocation.ToArray();

if (matches.length == 0) {
 // Tell the user no match.
} else {
 // Display all matches made.
 // 
}
 
Share this answer
 
v2
I have also tried something for you, please have a look

C#
class Travel
{


    string[] travellers_name = new string[8];
    public string[] departure_location = new string[4];
    public string[] arrival_location = new string[4];
    int[] mobileno = new int[8];

    public Travel()
    {

        departure_location[0] = "Phuket";
        departure_location[1] = "Amsterdam";
        departure_location[2] = "Mumbai";
        departure_location[3] = "Thailand";

        arrival_location[0] = "1.Bangkok";
        arrival_location[1] = "2.Damascas";
        arrival_location[2] = "3.Sri Lanka";
        arrival_location[3] = "4.Peshawar";
    }
}
static void Main()
{
    string welcome_msg = "Welcome to Sharp Travel Planner .\nPlease select your dream destination\n";
    Travel display_location = new Travel();
    Console.WriteLine(welcome_msg);
    for (int i = 0; i < display_location.departure_location.Length; i++)
        Console.WriteLine(display_location.arrival_location[i]);

    string input = Console.ReadLine();
    int selectedIndex = 0;
    if (!int.TryParse(input, out selectedIndex))
    {
        Console.WriteLine("InValid input!");
        Console.ReadKey();
        return;
    }
    if (selectedIndex > display_location.arrival_location.Count())
    {
        Console.WriteLine("InValid input!");
        Console.ReadKey();

        return;
    }
    var selection = display_location.arrival_location[selectedIndex - 1];

    bool res = display_location.arrival_location.Contains(selection);


    if (res)
        Console.WriteLine("Your choice is {0}", selection);
    else
        Console.WriteLine("Destination not available");

    Console.ReadKey();
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900