【问题标题】:How to for-loop or while-loop a set a numbers like this [closed]如何循环或循环设置这样的数字[关闭]
【发布时间】:2014-08-08 01:57:03
【问题描述】:

我想循环一组数字并更改它们在每一行中的位置。它读取一系列整数(最多 10 个),直到从键盘输入了一个非整数。我的预期结果是这样的:

>> 4 0 3 4 2 q
4 0 3 4 2
0 3 4 2 4 
3 4 2 4 0
4 2 4 0 3
2 4 0 3 4

谁能教我如何处理它?提前致谢。

【问题讨论】:

  • 您究竟在哪里卡住了?请张贴您的尝试,或者尝试在纸上写下您可能会如何做到这一点。
  • 我卡在 forlooping 部分。任何人都可以回答我的问题并教如何解决它?
  • 看起来像家庭作业。你为什么不发布你到目前为止所拥有的东西,你可能会得到一些帮助。这里的专业开发人员都没有兴趣为你写作业。

标签: java for-loop


【解决方案1】:

借助一些模运算知识,您可以将数组折叠成一个圆圈。观察每个索引的起点从上一行的起点向右移动一个位置。所以你这样做你的循环是这样的:

n := length of the array
for i = 0 to n-1 (assuming the array is zero-based)
    j := i
    do loop
        print(array[j])
        j := j + 1
        j := j%n
    until j = i
end for

这是一个独立于语言的伪代码。使其适应您正在编码的任何语言。

【讨论】:

  • 我试过了,但还是有错误。你能展示如何用java编程吗?
  • @alfred 在我知道你尝试了什么之前,我不能这样做。
【解决方案2】:

这是一种可以随意移动数字的方法。我冒昧地发表评论是为了让您更好地了解正在发生的事情。

public static void shift(int[] numbers) {
    //Store the first element
    int first = numbers[0];
    //Start for-loop at the beginning of the array, stop before the last element
    for (int i = 0; i < numbers.length - 1; i++)
        //Take the number at the next index (i + 1) and store it in the current index (i)
        numbers[i] = numbers[i + 1];
    //Don't forget about the first number!
    numbers[numbers.length - 1] = first;
}

下面的sn-p应该把数组的内容改成{0, 3, 4, 2, 4}

shift(new int[] {4, 0, 3, 4, 2})

这是一个完整的、可运行的类文件。

import java.util.Arrays;
public class Shift {
    public static void main(String[] args) {
        int[] numbers = new int[] {4, 0, 3, 4, 2};
        shift(numbers);
        System.out.println(Arrays.toString(numbers));
    }

    public static void shift(int[] numbers) {
        //Store the first element
        int first = numbers[0];
        //Start for-loop at the beginning of the array, stop before the last element
        for (int i = 0; i < numbers.length - 1; i++)
            //Take the number at the next index (i + 1) and store it in the current index (i)
            numbers[i] = numbers[i + 1];
        //Don't forget about the first number!
        numbers[numbers.length - 1] = first;
    }
}

编辑:

要使用名为list 的ArrayList,可以使用以下sn-p:

list.add(list.remove(0));

这是因为ArrayList.remove(int) 将返回从数组中移除的对象,所以我们可以将其添加到末尾。

【讨论】:

  • 你能清楚地展示你是如何在java中输入的吗?当我在我的程序中输入它时它不起作用。
  • 但是使用 arrayList 怎么样?因为我希望这个程序对所有整数都运行,谢谢!
  • 使用ArrayList 会使这变得微不足道。您需要做的就是使用list.add(list.remove(0));
猜你喜欢
  • 2018-02-20
  • 1970-01-01
  • 2021-02-03
  • 2021-04-02
  • 1970-01-01
  • 2019-03-23
  • 2016-07-27
  • 2019-01-29
  • 2014-07-22
相关资源
最近更新 更多