在java中以特定方式增加数组中的值

时间:2014-04-29 23:31:19

标签: java arrays numbers sequence

我想创建一个程序,它将把我们将拥有的类别作为输入,例如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只猫及其最大值,但要保持相同的逻辑。

我希望你能帮助我。抱歉我的英语不好。

1 个答案:

答案 0 :(得分:0)

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

  1. 遍历一个数组(大小为3),从最后一个插槽[2]开始,到第一个插槽[0]结束。
  2. 对于每个插槽,打印到控制台从0到该点的值(第一次从0到3)
  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);
             }
        }
    }
    

    至于格式化,这是你的决定。稍微弄清楚它,你会熟悉它。

    它具有类似阵列的风格。如果max为2,则结果为'0,1',而不是'1,2'。 要更改此设置,请更改计数器的开始位置,而不是counter < array[i],条件必须为counter <= array[i]