【问题标题】:How to search in String Array in android? [closed]如何在android中的字符串数组中搜索? [关闭]
【发布时间】:2015-06-17 14:43:37
【问题描述】:

我想在一个数组中搜索,我的代码是这样的:

public class A
{   
    public String [] Names;
    public A( List<String> listSp)
        {
            Names = new String[listSp.size()];
            listSp.toArray(Names);
        }
      public int numberOfState(String s)
        {

            int counter = 0;
            while (Names[counter] != s)
            {
               counter ++;  
            }
            return counter;
            }

并在此代码中使用 A 类:

public class Main extends Activity
{
...
   List<String> l = new ArrayList<String>();
   l.add("a");
   l.add("b");
      A objA = new A(l);
    int i = objA.numberOfState("b");
...
}

并且在运行应用程序并使用这部分时,一直显示此错误:

很遗憾,Main 已停止

我该怎么做?

【问题讨论】:

  • 这里有错误while (Names[counter] != s应该是while (Names[counter] != s)跨度>
  • int i = objA.numberOfState("b");
  • @oop12 下次请在您发布的行之后添加任何内容(不幸的是,Main 已停止),以便我们可以看到抛出了什么异常并更好地帮助您。事实上,如果你能将它添加到这个问题中,我会非常喜欢它。
  • 您没有使用for 循环或String.equals() 是否有原因?
  • 谢谢,但我的问题是:while 循环中的条件不起作用。我该怎么做?

标签: java android arrays algorithm oop


【解决方案1】:

问题是“越界”,您需要检查 counter 的值是否小于数组长度(或大小)的值。

你的代码应该是这样的:

public int numberOfState(String s) {
  int counter = 0;
  while (Names[counter] != s && counter < Names.length) {
    counter ++;  
  }
  return counter;
}

【讨论】:

  • @oop12 你有预付款吗?你会测试我的答案吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-27
  • 2014-09-02
  • 2016-12-01
  • 1970-01-01
  • 2011-07-22
相关资源
最近更新 更多