如何将用户输入作为字符串并检查数组以产生一些消息? [英] How to take user input as string and check against an array to produce some message ?

查看:56
本文介绍了如何将用户输入作为字符串并检查数组以产生一些消息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个程序,它接受用户输入并基于它提供一些结果。



输入采用sting变量的形式,并检查存储在数组中的字符串。

如果输入与这些存储的变量匹配,则显示成功消息或显示错误消息。



问题是,当输入匹配存储在数组中的值以及其他一些字母作为输入,即使它接受它并显示成功消息。



有关如何的任何建议更有效地改进代码吗?



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 ?

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");


		}


	}

}

推荐答案

以下是验证输入的示例:
Here's an example of how you might validate input:
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;
}

注意:



1.将用户输入转换为小写并将其与较低位置的目的地名称进行比较例如,用户可以有更多余地在案例方面打字错误。



2.退出您在此处看到的Console应用程序的代码只是占位符。



控制台应用程序imho的真正工作是获得循环结构设置,以便让用户重复数据输入。 ..直到它们成功,或者它们输入一些导致控制台终止的字符。

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.


更通用的解决方案是将目的地列表视为数据库和搜索输入的文字。如果这样做,那么您可以扩展目的地列表,而无需对测试进行硬编码。作为一般规则,硬编码是一件坏事,它可能导致各种不愉快,包括但不限于脆弱且难以维护的代码。



所以假设目的地列表在范围内,您可以执行以下操作:



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 :

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...

// 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.
 // 
}


我也尝试了一些东西,请看看



I have also tried something for you, please have a look

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();
}


这篇关于如何将用户输入作为字符串并检查数组以产生一些消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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