【问题标题】:how do i pass arrays in java我如何在java中传递数组
【发布时间】:2018-05-01 17:47:33
【问题描述】:

我正在尝试与 main 方法中定义的数组进行比较,并且需要将它们传递给 compareAnswers 方法我该怎么做?

这是我的代码:

/**********************************************
 *
 * 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]);
  }
 }
}

我知道我需要通过参考传递,但我的教授没有详细介绍这一点。任何帮助表示赞赏。

【问题讨论】:

  • 通过它:)
  • Java没有传引用,一切都是传值
  • 我会说everyghint 是通过引用传递但我能知道什么...
  • @AntonH 和 Antoniossss Java 总是按值传递 stackoverflow.com/questions/40480/… 按引用传递意味着你可以分配给传递的变量,但你不能
  • 请学习更好地格式化您的代码

标签: java arrays pass-by-reference


【解决方案1】:

如何在java中传递数组?

java 只有值调用; 但是java可以通过在需要的地方复制引用来传递引用。

例如

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.
     }
}

【讨论】:

    【解决方案2】:

    这样

    public static String compareAnswers(ArrayList<String> firstArray, ArrayList<String> secondArray)
    

    【讨论】:

      猜你喜欢
      • 2017-07-05
      • 2016-05-29
      • 2014-10-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-11-03
      相关资源
      最近更新 更多