【问题标题】:How do I print the array? [duplicate]如何打印数组? [复制]
【发布时间】:2022-01-10 20:16:22
【问题描述】:

除了我拥有数字数组并尝试打印它们的行(第 5-6 行)之外,所有代码都是正确的。如何打印数组?

public class PassedArray {

public static void passingArray(int[] nums) {

  int arr[] = {6, 3, 8, 89, 34, 89, 132, 76, 34, 89, 11, 9, 19} ; 
         System.out.println(nums);

int[] temp = new int[nums.length]; //create temporary array, temp, set the length of it equal to the original array
for(int i = 0; i < nums.length; i++) {
temp[i] = nums[i]; //set every value at temp equal to every number at i
//return nums;  
     }
int index = 0; //create integer index to keep track of index
for(int i = 0; i < temp.length; i++) {
    if(temp[i] % 2 ==0) { //if number at i divided by 2 yields remainder of 0
        nums[index] = temp[i]; //set number at index equal to temp at i, because temp at i is even
        index++; //Increment of index++ means index will increase by one each loop
                 //This is done because if this is not done, only the first number will be replaced 
    }
}

 for (int i = 0; index < temp.length; index++) {
     if (temp[i] % 2 != 0) { //if number at i divided by 2 does not yield remainder of 0
         nums[index] = temp[i]; //add the temp value to nums at index
         index++; //Increment of index++ means index will increase by one each loop
         
     }
 }
    
}

}

 

【问题讨论】:

  • 您应该编写一个循环语句来迭代数组元素并打印它们
  • 这能回答你的问题吗? What's the simplest way to print a Java array?
  • 我假设你的意思是你的 system.out.println(nums) 因为我看不到行号。但是这样做会给你哈希码。使用 Arrays.toString(nums)

标签: java arrays


【解决方案1】:

System.out.println(nums) 只给你哈希码。使用 Arrays.toString(nums)

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 2015-03-28
    • 2014-12-24
    • 2019-06-29
    • 2020-05-07
    相关资源
    最近更新 更多