【问题标题】:new function question for better interpretation新功能问题以更好地解释
【发布时间】:2021-08-13 09:40:16
【问题描述】:

希望更好地解释此信息或获取更多资源。

class Main {
public static void main(String[] args) {
    FileReader file = new FileReader("C:\\test\\a.txt");
    BufferedReader fileInput = new BufferedReader(file);
      
    // Print first 3 lines of file "C:\test\a.txt"
    for (int counter = 0; counter < 3; counter++) 
        System.out.println(fileInput.readLine());
      
    fileInput.close();

【问题讨论】:

  • 嗨@doug22 - 你已经返回了数组 - return values。根据您要打印的内容,您对数组执行 for 循环并打印出您想要的内容?
  • 这能回答你的问题吗? What's the simplest way to print a Java array?
  • 我不完全确定问题是什么,但是如果您说“打印了数组的地址”,您使用的是System.out.println(values)吗?如果是这样,您必须改用System.out.println(Arrays.toString(values))
  • 我猜你可能需要在你的课程中使用override method 'toString',包括AddressAgencyProperty

标签: java arrays return


【解决方案1】:

您解释为数组地址的可能是它的哈希码,它是Object 的默认实现toString() 的一部分。数组是一种对象,任何没有实现自己的toString()的对象在打印时都会以这种方式显示。

要打印内容,您必须遍历它们。一种方法是

System.out.println(
    Arrays.stream(values).collect(Collectors.joining(","))
    );

还有一点:如果您需要一个方法来返回多个值,返回Collection(或List 之类的子类型)更为惯用,因为它们在Java 中更易于使用。这也使您不必先循环两次数据以确定必要的大小。

【讨论】:

    【解决方案2】:
    public Property[] getPropertiesBetween(int minUsd, int maxUsd) {
        int counter = 0;
        int a = 0;
        for (Property land : properties.values()) {
            if (land.getPriceUsd() > minUsd && land.getPriceUsd() < maxUsd) {
                counter++;
            }
        }
        Property[] values = new Property[counter];
        for (Property land : properties.values()) {
            if (land.getPriceUsd() > minUsd && land.getPriceUsd() < maxUsd) {
                values[a] = land;
                a++;
            }
        }
    
       for(int i : values) {
          System.out.println(i);
        }
    
    
        return values; 
    }
    

    【讨论】:

      【解决方案3】:
      import java.util.Arrays;      
      public class ReturnArray1
          {  
           public static void main(String args[])  
           {  
              int[] a=numbers();           //obtain the array  
              for (int i = 0; i < a.length; i++) //for loop to print the array  
                 System.out.print( a[i]+ " ");     
           }  
           public static int[] numbers()  
           {  
              int[] arr={5,6,2,8,3,1,4,7,9,0};  //initializing array  
              return arr;  
           }  
      
          }  
      

      该方法返回一个整数类型的数组。

      【讨论】:

        猜你喜欢
        • 2012-05-22
        • 1970-01-01
        • 2011-01-09
        • 2016-06-21
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多