【问题标题】:How to make the return false if the arraylist already have the string present in class?如果arraylist已经在类中存在字符串,如何使返回为false?
【发布时间】:2014-12-18 01:54:22
【问题描述】:

我是编码新手。 如果添加的字符串已经在数组列表中,我如何返回 false? 例如,如果您在班级中有一个狗名列表,并且您在列表中添加了新的狗名,但当列表中已经有相同的狗名时不添加它?

【问题讨论】:

  • 请发布您的代码以获得个性化答案。

标签: string arraylist duplicates


【解决方案1】:

解决方案:

您可以使用for 语句来遍历您的数组列表:

public static bool checkArray(string dogName)
{
   for int i=0; i<arrayName.Length; i++) // basic for loop to go through whole array
   {
       if (arrayName[i] == dogName) //checks if array value at index i is the dog's name
       {
          return true; //if it is, return true
       }
   }
   return false; //gone through whole array, not found so return false
}

这意味着你可以通过

调用你的方法
 string Name = "myDogsName";
 bool isAlreadyPresent = checkArray(Name);

注意

  • 这是用 C# 编写的,因此其他编码语言会稍微 它们的语法不同。
  • isAlreadyPresent 将包含一个布尔值,如果狗是 存在与否
  • 我已经(出于学习目的)在(可能)一个 低效的方式,但应该让您了解正在发生的事情 在每个阶段。

i++

i++ 可能会使新程序员感到困惑,但实际上它与写作相同

i = i + 1;

这也适用于i--

i = i - 1;

甚至i*=2;

i = i * 2;

【讨论】:

    猜你喜欢
    • 2021-11-10
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2011-07-29
    • 2021-12-30
    相关资源
    最近更新 更多