переменная, возможно, не была инициализирована ... как увеличить область? [Дубликат]

1

Я продолжаю получать сообщение об ошибке:

error: variable aryResponse might not have been initialized
                if(answers.charAt(i) == aryResponse[i].charAt(i))

Я думаю, это потому, что я инициализирую переменную в цикле while. Однако я не знаю, как это исправить?

Как увеличить объем переменной, в то время как мне нужно, чтобы она была инициализирована значением, заданным циклом?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

class ExamAnalysis
{
    public static void main(String[] args) throws FileNotFoundException
    {
                    Scanner in = new Scanner(System.in);
                    System.out.println("Welcome to Exam Analysis.  Let begin ...");
                    System.out.println();
                    System.out.println();
                    System.out.print("Please type the correct answers to the exam questions, one right af$
                    String answers = in.nextLine();
                    int answersLength = answers.length();
                    System.out.println();
                    System.out.print("What is the name of the file containing each student responses to$
                    String temp = in.nextLine();
                    File file = new File(temp);
                    Scanner in2 = new Scanner(file);
/*Code Relevant To This Question Begins Here */
                    int lines = 0;
                    String[] aryResponse;
                    while (in2.hasNextLine())
                    {
                            String line = in2.nextLine();
                            aryResponse = new String[lines];
                            aryResponse[lines] = line;
                            System.out.println("Student #" + lines + " responses:  " + line);
                            lines++;
                    }
                    System.out.println("We have reached \"end of file!\"");
                    System.out.println();
                    System.out.println("Thank you for the data on " + lines + " students.  Here the ana$
                    int[] aryCorrect = new int[lines];
                    for (int i = 0; i < answersLength; i++)
                    {
                            if(answers.charAt(i) == aryResponse[i].charAt(i))
                            {
                                    aryCorrect[i] ++;
                            }
                    }
       }
}
Теги:
arrays

3 ответа

2
Лучший ответ

Изменить это

String[] aryResponse;

в

String[] aryResponse = null;

И не забудьте проверить, что aryResponse не является null,

if (aryResponse != null) {
  for (int i = 0; i < answersLength; i++) {
    if (answers.charAt(i) == aryResponse[i].charAt(i)) { // what is this testing?
      aryCorrect[i]++;
    }
  }
}

Это необходимо, потому что

while (in2.hasNextLine()) { // <-- might not be true
  // so this doesn't happen.
}
  • 0
    Спасибо, а также спасибо всем остальным. Тем не менее, я получаю массив из-за ошибки после, и я не могу понять, почему? Также третья строка сравнивает две строки символ за символом.
1

Если я понял ваш код, aryResponse имеет несколько строк, если переменная никогда не была инициализирована внутри цикла while, это означает, что у вас есть 0 строк, поэтому было бы достаточно сделать две вещи:

1- инициализировать aryresponse для null:

String[] aryResponse = null;

2 - добавьте эту строку в конец цикла while:

if(aryResponse == null) aryResponse = new String[0];
0

Просто инициализируйте его вне цикла

String[] aryResponse=null;

Теперь выделите память на внутренний цикл aryResponse

aryResponse = new String[n]; //n is the size of array

Ещё вопросы

Сообщество Overcoder
Наверх
Меню