-4

I am trying to compare to arrays defined in the main method and need to pass them to the compareAnswers method how do I do this?

here is my code:

/**********************************************
 *
 * Daniel Wilson
 * 
 * CIS129
 * 
 * November 15 2017
 * 
 * Compaires test answers against correct answers 
 * 
 * ********************************************/

import java.io.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;

public class CIS129_DanielWilson_PC6 {

public static void main(String args[]) {

  final int SIZE = 20;
  String[] givenAnswers = new String[SIZE];
  String[] correctAnswers =      { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D", "B",  "C", "D", "A", "D", "C    ", "C", "B", "D", "A"}; 
  String answers = compareAnswers();

  InputStreamReader input = new InputStreamReader(System.in);
  BufferedReader reader = new BufferedReader(input); 

  try{
    System.out.println(Arrays.toString(correctAnswers));
    for (int i = 0; i<SIZE; i++) {
    System.out.println("please enter your answer for question " + (i+1));
      givenAnswers[i] = reader.readLine();
    }
  }catch (IOException e){
            System.out.println("Error reading from user");
      }
}
public static String compareAnswers(){

List<String> tempList = new ArrayList<String>();
for(int i = 0; i < correctAnswers.length; i++)
{
    boolean foundString = false;
    for(int j = 0; j < givenAnswers.length; j++)
    {
        if(givenAnswers[j].equals(correctAnswers[i]))
        {
            foundString = true; 
            break;
        }
    }
    if(!foundString) 
        tempList.add(givenAnswers[i]);
}
String ammountRight[] = tempList.toArray(new String[0]);
for(int i = 0; i < ammountRight.length; i++)
{
    System.out.println(ammountRight[i]);
  }
 }
}

I understand I need to pass by reference but my professor didn't cover that in much detail. any help is appreciated.

Daniel Wilson
  • 3
  • 1
  • 1
  • 1

2 Answers2

0

how do i pass arrays in java?

java only has call by value; but java can just pass a reference by copying the reference where needed.

e.g.

public class Main{
     public static void main(String[] args){
            String[] arr = new String[size];
            // fill your array!

            Main.foo(arr);

     public static void foo(String[] a){
          // do something with your array.
          // if you change a value of the array, 
          // the array in main will be changed too.
     }
}
-1

Like this

public static String compareAnswers(ArrayList<String> firstArray, ArrayList<String> secondArray)
NickDim
  • 17
  • 3