【问题标题】:Java array loop roundJava 数组循环循环
【发布时间】:2018-01-21 03:26:54
【问题描述】:

我在 Java 中有一个数组,想在数组中找到下一个元素。

我想继续获取数组中的下一个元素。而不是到达数组的末尾并停止,我怎样才能让它再次循环到数组的开头并继续这样做?

【问题讨论】:

  • 显示您目前拥有的代码。这是相当广泛和模糊的。你想让循环永远循环吗?
  • 到达末尾时将索引变量重置回0。你知道,使用if 语句。真的可以这么简单。
  • @David992 这个问题有点奇怪,你的意思是要实现一个无限循环?你结束循环的条件是什么?您可能想告诉我们为什么需要这样的循环。

标签: java arrays


【解决方案1】:

例如,假设我们有一个字符串数组。

让我们考虑一些方法。

使用显式索引检查

另一种方法是使用显式检查索引是否超出最大值并将其重置以将索引保持在所需的范围内。

请考虑以下实施草案:

public class Program {
    public static void main(final String[] args) throws InterruptedException {
        final String[] words = new String[] {
            "Hello",
            "World",
            "Goodbye",
            "World"
        };

        int index = 0;
        while (index < words.length) {
            System.out.printf(
                "Index: %d; Value: %s.%n",
                index,
                words[index]
            );

            ++index;
            if (index == words.length) {
                index = 0;
            }

            Thread.sleep(1000);
        }
    }
}

使用模运算

请考虑以下实施草案:

public class Program {
    public static void main(final String[] args) throws InterruptedException {
        final String[] words = new String[] {
            "Hello",
            "World",
            "Goodbye",
            "World"
        };

        int index = 0;
        while (index < words.length) {
            System.out.printf(
                "Index: %d; Value: %s.%n",
                index,
                words[index]
            );

            ++index;
            index %= words.length;

            Thread.sleep(1000);
        }
    }
}

这里的关键是使用取模运算(除法后求余数)来保持索引在需要的范围内。

两种方法的注意事项

  1. 如果数组不为空,则存在无限循环。
  2. index &lt; words.length 作为 while 循环条件可以正确处理空数组。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2017-03-21
    • 1970-01-01
    • 2019-02-13
    • 2011-12-02
    • 2015-08-28
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多