0

So to summarize my problem, I want the function int[] get_marks() to be able to return the array, but I don't know how to get my ArrayList marks to convert into an array which I can use the return thing for. I need the arraylist to be converted because I need to be able to find the frequency and mode of the array (parts of the code I have not started because I can't figure out how to convert the arraylist).

Below is my comment less code so far.

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();
  }
}
Joe
  • 9
  • 2
  • 1
    You can convert the arrayList into an array and return that. Your question is not very clear to me. You said you want to return a function ? – Ezio Jan 13 '21 at 06:31
  • Does this answer your question? [Returning Arrays in Java](https://stackoverflow.com/questions/12869741/returning-arrays-in-java) – Umair Mubeen Jan 13 '21 at 06:31
  • Create an int[] the length of the ArrayList then put each element of the ArrayList into the new array. Then return the array. – NomadMaker Jan 14 '21 at 15:50

2 Answers2

0

Why not just return the ArrayList marks?

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

Also, you could make the method return void. Is there any reason you need it to return a value in main?

To elaborate, if you make it void, it will just do all the calculations and culminate in System.out.println("Your Marks are: " + marks);. Given your code, is that not what you want? If so, make get_marks() return void:

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

Why do you need the get_marks() method? You may not have posted all your code, but if this is all your code, just get rid of get_marks() and put it all in main(). If all main() does is call get_marks(), consolidate the methods.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cole Henrich
  • 155
  • 3
  • 17
  • thats just one part of the code. theres more parts where i need to find frequency and mode of the array which is why I can't have it as a void function – Joe Jan 13 '21 at 07:13
0

There's no reason not to simply return an ArrayList<Integer> or even better a List<Integer>. If you insist on returning an int[], your question is a duplicate of this.

Rubydesic
  • 3,386
  • 12
  • 27