【问题标题】:how to make an array function return a value [duplicate]如何使数组函数返回一个值[重复]
【发布时间】:2021-01-13 06:28:32
【问题描述】:

所以总结一下我的问题,我希望函数 int[] get_marks() 能够返回数组,但我不知道如何让我的 ArrayList 标记转换为可以使用返回的数组的事情。我需要转换arraylist,因为我需要能够找到数组的频率和模式(部分代码我没有开始,因为我不知道如何转换arraylist)。

以下是我到目前为止的注释较少的代码。

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;

class Main {

  public static int[] get_marks(){
    Scanner input = new Scanner(System.in);

    ArrayList<Integer> marks = new ArrayList<>();
    final int FLAG = -1;
    int entries = 0;

    System.out.println("Enter your marks. Type -1 when done.");

    while (entries != FLAG){
    entries = input.nextInt();
    
    if (entries >=0 && entries <= 100){
      marks.add(entries);
    } else if (entries == FLAG) {
      break;
    } else {
      System.out.println("Invalid entry. Marks must be between 0-100.");
      }
    }
    input.close();

    System.out.println("Your Marks are: " + marks);
  }

  public static void main(String[] args) {
    get_marks();
    
    System.out.println();
  }
}

【问题讨论】:

  • 您可以将 arrayList 转换为数组并返回。你的问题对我来说不是很清楚。你说你想返回一个函数?
  • 这能回答你的问题吗? Returning Arrays in Java
  • 创建一个长度为 ArrayList 的 int[],然后将 ArrayList 的每个元素放入新数组中。然后返回数组。

标签: java arrays function arraylist


【解决方案1】:

没有理由不简单地返回 ArrayList&lt;Integer&gt; 或者更好的 List&lt;Integer&gt;。如果您坚持返回int[],您的问题是duplicate of this

【讨论】:

  • 这对我不起作用
【解决方案2】:

为什么不只返回 ArrayList 标记?

public static ArrayList<Integer> get_marks(){return marks}

此外,您可以使方法返回无效。你有什么理由需要它在 main 中返回一个值吗?

详细地说,如果你把它设为void,它只会做所有的计算并在System.out.println("Your Marks are: " + marks); 中达到高潮。给定您的代码,这不是您想要的吗?如果是这样,让get_marks() 返回 void:

public static void get_marks() {//run the code, print the marks, etc.}

为什么需要get_marks() 方法?您可能没有发布所有代码,但如果这是您的所有代码,只需删除 get_marks() 并将其全部放入 main()。如果main() 所做的只是调用get_marks(),则合并这些方法。

【讨论】:

  • 这只是代码的一部分。还有更多部分我需要找到数组的频率和模式,这就是为什么我不能将它作为 void 函数
猜你喜欢
  • 1970-01-01
  • 2013-11-12
  • 1970-01-01
  • 1970-01-01
  • 2019-09-06
  • 2018-10-07
  • 1970-01-01
  • 2019-10-20
  • 1970-01-01
相关资源
最近更新 更多