我的代码没有返回我期望的值

时间:2015-04-23 09:35:23

标签: c# string equals

您好我最近决定开始学习C#,我制作了这个快速程序,以熟悉其编写方式。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpTesting
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] Names = new string[4] { "Ben", "Thor", "Zoe", "Kate" };
            Names[0] = "ben";
            Names[1] = "thor";
            Names[2] = "zoe";
            Names[3] = "kate";
            int Max = 4;
            int Current = 0;
            bool Found = false;
            Console.WriteLine("What player are you looking for?");
            string PlayerName = Console.ReadLine();
            while ((Found = false) && (Current <= Max))
            {
                if (Names[Current].Equals(PlayerName))
                {
                    Found = true;
                }else
                {
                    Current++;

                }
                Console.Write(Names[Current] + PlayerName);
            }
            if (Found == true)
            {
                Console.WriteLine("Yes, they have a top score");
                Console.Write(PlayerName);

            }
            else if (Found == false)
            {
                Console.WriteLine("No, they do not have a top score");
                Console.Write(PlayerName);
            }
            else
            {
                Console.WriteLine("ERROR");
            }
            Console.ReadKey();
        }
    }
}

每次运行代码时,即使我输入与数组中某个名称相同的字符串,它也会返回“否,它们没有最高分”。我认为问题可能在于我检查'PlayerName'和数组名称是否相同但我不确定的方式。任何帮助将不胜感激。

5 个答案:

答案 0 :(得分:1)

while ((Found = false) && (Current <= Max))

应该是

while ((Found == false) && (Current <= Max))

顺便说一句,开头有大写字母的名字通常用于上课。

答案 1 :(得分:0)

您需要将if子句更改为:

if (Names[Current] == PlayerName)

答案 2 :(得分:0)

将您的时间条件更改为:

while ((Found == false) && (Current <= Max))

答案 3 :(得分:0)

(Found = false)

是一个错误。如果需要比较,请使用==

  (Found == false)

=意图将false值赋给Found变量

所有代码都可以替换为

if (Names.Contains(PlayerName ) )

答案 4 :(得分:0)

问题是由于Capital Case。

更改&#34; Equals&#34;与ignoreCase进行比较的方法

if(string.Compare(PlayerName, Names[Current], true) == 0)

无论如何其他用户说:Found = false是错误的。 你必须写Found == false