如何从不同的方法打印多个变量?

问题描述 投票:0回答:3

我想创建一个显示三个值的print语句。 1)计数器变量,显示迭代次数。 2)阵列记录器,记录元素的值和3)这些元素的值+ 5。

有一种更改方法,它接受数组中的所有值并向它们添加5。我只是无法理解如何根据计数器变量和数组元素计数器打印此值。这可能吗?

int sam[] = {1,2,4,5,6,4,3,67};

change(sam);
for (int y:sam) {
    for(int counter =0; counter<sam.length;counter++) { 
        //this is where I wish to print out the 3 elements
        System.out.println(counter+ "\t\t" + sam[counter]+y);
    }
}

public static void change(int x []) {
    for(int counter=0; counter<x.length;counter++)
     x[counter]+=5;
}
java arrays for-loop arraylist
3个回答
1
投票

一切都很好,除了sam[counter] + y被评估为整数值,因为两个参数都是整数。你需要字符串连接:

System.out.println(counter + " " + sam[counter] + " " + y);

或类似的东西(使用formatter):

System.out.printf("counter = %d, sam[counter] = %d, y = %d\n", counter, sam[counter], y);

%d是一个小数参数,\n是一个新的行。

编辑:关于你的代码。如果要为数组中的每个元素输出以下行格式

counter     sam[counter]        sam[counter] + 5

然后只是使用

int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
    System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] + 5));
}

这将以所需格式打印值。

0       1       6
1       2       7
2       4       9
...

或者,如果要更改数组,但能够打印旧值,请尝试以下操作:

int sam[] = {1,2,4,5,6,4,3,67};
for (int counter = 0; counter < sam.length; counter++) {
    System.out.println(counter + "\t\t" + sam[counter] + "\t\t" + (sam[counter] += 5));
}

这里qazxsw poi将每个元素递增5并返回新值。


0
投票

摆脱这个外圈(sam[counter] += 5)

这应该工作:

for (int y:sam)

0
投票

你的问题有点难以解释,但只是放弃外循环,不要“+ y”

抓一点。您认为改变程序对您有什么影响?您是否想要一个具有原始值的数组和另一个具有更改值的数组,然后可以访问这两个数组?

© www.soinside.com 2019 - 2024. All rights reserved.