简体   繁体   English

基于另一个数组的Java打印数组

[英]Java Printing Array based off Another Array

I am trying to print an Array, however, I am needing to print the right array, off of an integer from another array. 我试图打印一个数组,但是,我需要打印正确的数组,而不是另一个数组的整数。

(ie) arrayInt contains 2,4,6,5,1 . (即) arrayInt包含2,4,6,5,1 I want to use a for loop to print the numbers. 我想使用for循环来打印数字。 Then, I want to print the double that is corresponding to the int . 然后,我要打印对应于intdouble int arrayInt , that has been sorted, is 1,2,3,4,5 and arrayDouble, that hasn't been sorted, is 2.6,6.9,1.3,2.4,9.8 . arrayInt ,已排序,是1,2,3,4,5和arrayDouble,尚未排序,是2.6,6.9,1.3,2.4,9.8 After I print arrayInt[0] , which is 1 , I want to print the corresponding (in this case the 1 st ) value in arrayDouble . 在打印为1 arrayInt[0]之后,我想在arrayDouble打印相应的(在本例中为1st )值。

The following code is what I came up with: 以下是我想出的代码:

for (int k = 0; k < 7; k++)
    System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[(sortedNum[k])]);

I think you kinda answered your own question here, have you tried the code that you specified? 我认为您在这里回答了自己的问题,是否尝试过指定的代码?

If I understood correctly you want to print something from an array based on the index that is stored in another array, if so, the following code should work (notice I removed the parenthesees from your code): 如果我正确理解了您想要基于存储在另一个数组中的索引从数组中打印出某些内容的情况,则可以使用以下代码(注意,我从代码中删除了括号):

for (int k = 0; k < 7; k++) {
    System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]);
}

This is assuming sortedNum is an array of ints and arrayWeight is an array of floats. 假设sortedNum是一个整数数组,而arrayWeight是一个浮点数组。

You have to check size of second array before trying to fetch value from it 您必须先检查第二个数组的大小,然后才能尝试从中获取值

for (int k = 0; k < 7; k++) { 
if (sortedNum[k] < arrayWeight.length)
System.out.printf("%d %.2f\n", sortedNum[k], arrayWeight[sortedNum[k]]); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM