【问题标题】:Array size counting – Android, Java数组大小计数——Android、Java
【发布时间】:2014-04-07 18:25:49
【问题描述】:

我整天都在担心这个问题:

我有一个字符串数组。解析字符串行后

str3.split("\\n"));

然后我想用 Next/Previous 按钮让它显示。

字符串文本 = null;

    if (rotation){

        if (count < fullString.length) {

            for (int i = count; i <= fullString.length - 1; i++) {
                text = fullString[i];
                ++count;
                if (text.trim().length() > 0 & !text.isEmpty()){
                    return text;

                }
            }
        }
    }

    if (!rotation) {

        if (count > 0) {
            for (int i = count ; i >= 0; i--) {
                text = fullString[i - 1];
                --count;
                if (text.trim().length() > 0 & !text.isEmpty()){
                    return text;
                }
            }
        }
    }

它可以,但需要按两次按钮(如果按“下一步”,我应该按“上一个”两次)。 我知道,这是个愚蠢的问题,但我找不到问题所在。

【问题讨论】:

  • 你为什么要减少和增加计数两次?
  • 另外,代码中对fullString 的第二次访问可能会越界(最后一次迭代是i=0,而您使用索引i-1
  • 如果您想要更全面的答案,了解按钮应该做什么会有所帮助...
  • @Mifeet,不,它没有
  • @whisperofblood 到目前为止还没有。

标签: java android arrays cycle


【解决方案1】:

问题是你与你在循环中赋予count 的含义不一致。

count 的可能含义

1。 count 表示下一项,即您要返回的项。

在这种情况下,您的循环应该分别从count+1count-1 开始,并且都应该使用fullString[i]

2。 count代表当前选中的项目,你想要下一个。

在这种情况下,您的循环都应该从count 开始,并且您应该引用fullString[i+1](第一个循环)或fullString[i-1](第二个循环)。您还必须小心更改循环的结束条件,这样i+1i-1 就不会越界。

当前问题:混合方法

在代码的当前状态下,您可以混合使用两种方法:

  • 在第一个循环中,您从count 开始,但使用fullString[i]。由于您没有立即增加计数,因此按下按钮无用。

  • 在第二个循环中,您使用第二个选项而不更改结束条件。这将在 count 为 0 时触发 ArrayIndexOutOfBoundException(或者您在索引 0 之前找不到非空字符串),正如 @Mifeet 在您决定忽略的评论中指出的那样。

改进

另外,既然你无论如何都要递增/递减count,我会直接使用它而不是添加索引i。这使您的循环更干净,并且您还可以摆脱 if 计数。

if (rotation) {
    for (count++; count <= fullString.length - 1; count++) {
        text = fullString[count];
        if (text.trim().length() > 0) {
            return text;
        }
    }
}

if (!rotation) {
    for (count--; count >= 0; count--) {
        text = fullString[count];
        if (text.trim().length() > 0) {
            return text;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2015-02-18
    • 2017-08-13
    • 1970-01-01
    • 2016-03-11
    • 2010-10-17
    • 2010-12-11
    • 2018-02-14
    相关资源
    最近更新 更多