2016-09-02 1 views
-4

과제를 작성 중이며 여기에 내 코드를 게시해도 괜찮은지 모르지만 문제를 설명하기 위해 최선을 다할 것입니다. 나는 별도의 프로그램에서 일련의 학생들의 대답을 받아들이고 내가 쓰고있는 수업에서 초기화 한 정답의 배열과 그 배열을 비교하는 수업을 작성해야한다. 그런 다음 클래스는 메소드를 통해 올 바르고 잘못된 답의 양을 계산 한 다음 결과를 출력하기 위해 프로그램으로 다시 보냅니다. 문제가있는 부분은 학생이 잘못한 질문의 질문 번호를 저장하는 배열을 만드는 방법입니다. 나는 for 루프를 사용하여 생성자의 두 배열을 비교하고 잘못된 배열과 관련된 질문 번호를 저장하기 위해 새 배열을 초기화했다. 일반적으로 배열을 메서드 헤더의 인수로 전달하지만 프로그램은 클래스 작동 방법에 인수가없는 것으로 메서드가 정의되어 있고 생성자에서 메서드로 배열을 전달하는 다른 방법을 알지 못합니다. 죄송합니다.이 질문이 멍청한 소리로 들린다면 아마도 그럴 것입니다. 그러나 나는 이것을 인정하고 싶습니다. 기본적으로 인수로 전달하지 않고 메서드에서 생성자로 초기화 된 배열에 액세스 할 수있는 방법이 있는지 궁금합니다.Java 메서드에서 배열을 인수로 전달하지 않고 참조하는 방법

public class Example { 
    private char[] correctAnswers; 
    private char[] studentAnswers; 
    private int count = 0; 

    // Constructor accepts an array of answers from the other program. 
    public Example(char[] answers) { 
     char[] correctAnswers = {'a', 'b', 'c'}; 
     int question_number = 1; 
     int[] missed = new int[3]; 
     // Copy answers array to studentAnswers array 
      *Insert code here 

     //Using a for loop I Compare the two arrays studentAnswers and 
     //correctAnswers and increment variables count and question_number 
     //and if a question is wrong I populate the missed array with 
     // the question_number 
      *Insert code here* 

     public int totalCorrect() { 
      return count; 
      } 

     public int[] totalIncorrect() { 
      incorrect = 3 - count; 
      return incorrect; 
      } 

     // This method can't accept any arguments 
     public int[] questionsMissed() { 
      return missed; // How do I access this array which is 
          // initialised in the constructor? 
      } 
+3

여기에 코드를 게시하는 것이 좋습니다. –

+1

빈 줄과 공백을 사용하여 코드 서식을 지정하십시오. – Tobb

+0

[ask] 및 [mcve] – xenteros

답변

0

내가, 당신이 아래와 같이 missed에 액세스 할 수 있어야합니다 아래의 코드의 코멘트에 몇 가지 제안을 추가했지만 그런 다음 클래스 Example를 인스턴스화하는 경우 missed 배열도 너무 초기화됩니다, 당신은 shouldn 여기에 NPE가 없습니다.

또한 missed = new int[3];은 어떤 값을 지정할 때까지 [0,0,0]과 같은 배열을 생성합니다.

public class Example { 

    private char[] correctAnswers; 
    private char[] studentAnswers; 

    private int[] missed; // here you're defining the array, this can be used throughout the class. 

    private int count = 0; 

    // Constructor accepts an array of answers from the other program. 
    public Example(char[] answers) { 
     correctAnswers = new char[]{'a', 'b', 'c'}; // Here, don't call char[] again because you've already defined this array as char[] earlier 
     int question_number = 1; 
     missed = new int[0]; // here you are initialising the array with 3 elements 

     // Copy answers array to studentAnswers array 
     *Insert code here 

     //Using a for loop I Compare the two arrays studentAnswers and 
     //correctAnswers and increment variables count and question_number 
     //and if a question is wrong I populate the missed array with 
     // the question_number 
     *Insert code here* 

     for(int i=0; i<studentAnswers.length(); i++){ 

      if(studentAnswers[i] != correctAnswers[i]){ 
       missed = addElement(missed, i); // Adding an element to the list, this isn't a good way to do it 
      } 

     } 

    } 

    public int totalCorrect() { 
     return count; 
    } 

    public int[] totalIncorrect() { 
     incorrect = 3 - count; 
     return incorrect; 
    } 

    // This method can't accept any arguments 
    public int[] questionsMissed() { 
     try { 
      return missed; // You can access this, and return only if it has been initialised before accessing this method. 
     } catch(NullPointerException e){ 
      System.out.println("the array wasn't initialised before accessing this method") 
     } 
    } 

    /** 
     * This method just takes the current array, makes a new one and adds an element to it, it's mocking Collections.add(E e) 
    */ 
    static int[] addElement(int[] a, int e) { 
     a = Arrays.copyOf(a, a.length + 1); 
     a[a.length - 1] = e; 
     return a; 
    } 

} 

편집 : 나는 당신이 일을하려고하지만, 여기에 배열을 사용하고 무엇을 달성 할 수있는 방법에 대한 몇 가지 더 제안에 추가 한 것은 정말 나쁜 선택처럼 보인다. 나는 Collections을 사용하는 것이 더 나을 것이라고 생각합니다. 3 답이 모두 잘못 되었다면 은 3 길이로 초기화 할 필요가 없기 때문에.

+1

당신은 나를 도울 수있는 시간을내어 주셔서 감사합니다. 그것은 지금 작동하지만 당신이 오류를 제안하는 것처럼 생성자에서 올바른 답변 전에 char [] 제거 할 때 : 식의 불법적 인 시작 그래서 그것을 다시 넣어하지만 int [] 전에 생성자에서 놓친 전에 제거한 당신의 예제에서 지금은 작동합니다 ... –

+0

@Doc_Apes 걱정할 필요가 없습니다. 그렇습니다. 결정된. 내가 지금까지해온 방식대로 사용하면 잘 작동합니다. – px06

+0

감사합니다 힙 나는 지금 일하고있다! 당신은 전설입니다! 계속 올려! –

0

어떤 방식 으로든 사용하려는 방법에 대해 액세스 할 수 있도록해야합니다.

  • 당신은 개체를 공개 할 수는
  • 사용하여 명령 또는 빌더 패턴 (reccommended되지 않음). 사실 이것은 여전히 ​​매개 변수로 추가하고 있지만 비어있는 cTor를 가져 와서 빌드/실행을 호출하기 전에 추가 할 수 있습니다. 나는 이것이 당신의 문제를 해결할 것이라고 생각합니다.
관련 문제