【问题标题】:Increase values in array in specific way in java在java中以特定方式增加数组中的值
【发布时间】:2014-04-29 23:31:19
【问题描述】:

我想创建一个程序,它将我们将拥有多少个类别作为输入,例如 3。

int [] n=new int[4];
n[1]=0; n[2]=0; n[3]=0;

然后它会询问每一个的最大值,例如:

int [] max=new int[4];
max[1]=2;
max[2]=4;
max[3]=3;

我想根据最大值创建一个数字序列。例如当n[3]==3; 然后n[2]++; 直到它达到它的最大值然后n[1]。我希望结果是这样的:

n[1]    n[2]    n[3]
0        0       0
0        0       1
0        0       2
0        0       3
0        1       0

直到达到值n[1]=2, n[2]=4, n[3]=3

输出示例如下:

From array slot #0: 0
From array slot #1: 0
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 1
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 2
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 3
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #0: 1
From array slot #1: 0
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 1
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 2
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

From array slot #1: 3
From array slot #2: 0
From array slot #2: 1
From array slot #2: 2

我最大的问题是我想动态地做。更具体地说,我想更改给定的类别,例如要求 4 只猫及其最大值,但要保持相同的逻辑。

我希望你能帮助我解决这个问题。并为我糟糕的英语感到抱歉。

【问题讨论】:

  • 只是为了确定,您故意忽略数组中的第 0 位?
  • 不..这不是我的问题。我可以通过在数组位置上添加 +1 来解决这个问题。在第一篇文章中检查我的问题,因为我是新成员,所以我无法回答我的问题。我编辑了第一个,看看我在找什么。

标签: java arrays numbers sequence


【解决方案1】:

如果这没有帮助,我很抱歉,不太确定你的目标是什么,但你想做的是:

  1. 遍历一个数组(大小为 3),从其最后一个槽 [2] 开始,到其第一个槽 [0] 结束。
  2. 对于每个插槽,从 0 到该位置的值(第一次从 0 到 3)打印到控制台

如果是这样,看看这个:

static int[] array = new int[3];
public static void main(String[] args) {
     array[0] = 2;
     array[1] = 4;
     array[2] = 3;

     printSequence(array.length);
}

static void printSequence(int howManyMaxes) {
    for(int i = howManyMaxes-1; i >= 0; i--) { //loops through array (from last to first)
         for(int counter = 0; counter < array[i]; counter++) { //loops from 0 to value
              System.out.println("From array slot #"+i+": "+counter);
         }
    }
}

至于格式化,那是你的决定。稍微弄一下,你就会熟悉了。

它以类似数组的样式计算。如果最大值为 2,则结果将为 '0, 1',而不是 '1, 2'。 要改变这一点,改变你的计数器开始的地方,而不是counter &lt; array[i],条件需要是counter &lt;= array[i]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-29
    • 2012-12-20
    • 2019-12-18
    • 1970-01-01
    • 2017-05-15
    • 1970-01-01
    • 2021-08-17
    相关资源
    最近更新 更多