여러 특성을 가진 질문 개체를 만들려고합니다.이 개체는 모두 텍스트 파일에 저장되고 StreamReader를 사용하여 검색됩니다.스트림 작성기에서 for 루프 사용
하나의 속성은 배열 Choices[]
입니다. 변수 배열 qType
의 값에 따라 배열을 채울 수 있어야합니다.
예를 들면 if qType = "button"
이면 Choices[]
은 파일에서 4 줄만 읽어야합니다. 반면 if qType = "dragdrop"
인 경우 Choices[]
은 파일에서 6 번 읽어야합니다. 지금까지 for 루프, case 문 및 if 문을 사용해 보았습니다.이 중 모두가 중단되었습니다. 누군가가 StreamReader를 방해하지 않고 이것을 어떻게 할 수 있는지 말해 줄 수 있습니까? 작동
을 Heres 코드 : 내가 사용하고있는 전체 코드
Choices = new string[]
{
for(int i=0; i<4; i++)
{
quizFileReader.ReadLine(), // expects a ;
}
}, // excepts a ;
을 Heres :
public string QuestionText, imgPath, hintTxt; // Actual question text.
public string[] Choices; // Array of answers from which user can choose.
public int Answer, qNum, linesToRead; // Index of correct answer within Choices.
public double difficulty; // Double that represents difficulty of each question
public List<Question> getQues() // reads questions from text file, assigns all strings in text file to index of List, returns the full list of questions
{
// Create new list to store all questions.
var questions = new List<Question>();
// Open file containing quiz questions using StreamReader, which allows you to read text from files easily.
using (var quizFileReader = new System.IO.StreamReader("PhysQuestions.txt"))
{
string line;
Question question;
// Loop through the lines of the file until there are no more (the ReadLine function return null at this point).
// ReadLine called here only reads question texts (first line of a question), while other calls to ReadLine read the choices.
while ((line = quizFileReader.ReadLine()) != null)
{
// Skip this loop if the line is empty.
if (line.Length == 0)
continue;
// Create a new question object.
// The "object initializer" construct is used here by including { } after the constructor to set variables.
question = new Question()
{
// Set the question text to the line just read.
QuestionText = line,
linesToRead = Convert.ToInt32(quizFileReader.ReadLine()),
Choices = new string[linesToRead];
for (int i=0; i < linesToRead; i++)
{
Choices[i] = await quizFileReader.ReadLineAsync();
}
hintTxt = await quizFileReader.ReadLineAsync();
difficulty = Convert.ToDouble(quizFileReader.ReadLine());
imgPath = quizFileReader.ReadLine();
};
// Set correct answer to -1, this indicates that no correct answer has been found yet.
question.Answer = -1;
// Check each choice to see if it begins with the '!' char (marked as correct).
for (int i = 0; i < 4; i++)
{
if (question.Choices[i].StartsWith("!"))
{
// Current choice is marked as correct. Therefore remove the '!' from the start of the text and store the index of this choice as the correct answer.
question.Choices[i] = question.Choices[i].Substring(1);
question.Answer = i;
break; // Stop looking through the choices.
}
}
// Check if none of the choices was marked as correct. If this is the case, we throw an exception and then stop processing.
if (question.Answer == -1)
{
throw new InvalidOperationException(
"No correct answer was specified for the following question.\r\n\r\n" + question.QuestionText);
}
// Finally, add the question to the complete list of questions.
questions.Add(question);
}
return questions;
}
}
다음
using (var quizFileReader = new System.IO.StreamReader("PhysQuestions.txt"))
{
string line;
Question question;
// Loop through the lines of the file until there are no more (the ReadLine function return null at this point).
// ReadLine called here only reads question texts (first line of a question), while other calls to ReadLine read the choices.
while ((line = quizFileReader.ReadLine()) != null)
{
// Skip this loop if the line is empty.
if (line.Length == 0)
continue;
// Create a new question object.
// The "object initializer" construct is used here by including { } after the constructor to set variables.
question = new Question()
{
// Set the question text to the line just read.
QuestionText = line,
qType = quizFileReader.ReadLine(),
// Set the choices to an array containing the next 4 lines read from the file.
Choices = new string[]
{
quizFileReader.ReadLine(),
quizFileReader.ReadLine(),
quizFileReader.ReadLine(),
quizFileReader.ReadLine(),
},
hintTxt = quizFileReader.ReadLine(),
difficulty = Convert.ToDouble(quizFileReader.ReadLine()),
imgPath = quizFileReader.ReadLine()
};
}
}
내가 작동하지 않습니다 그렇게하려고 노력 뭔가
안녕하세요, 도와 주셔서 고마워요, 정말 하하가 필요합니다. 죄송 합니다만, 나는 C#에 익숙하지 않고 'await'과 'async'에 익숙하지 않습니다. 내 코드를 구현하려고 할 때이 코드가 비동기에 있다는 메서드를 만들 것을 요청하는 오류가 발생했습니다. 메서드가 값 (즉 List qList)을 반환 할 수 있어야하므로이 작업을 수행 할 수 없습니다. 내 코드의 나머지 부분을 알려주고 내가 의미하는 바를 볼 수 있습니다. 다시 한번 감사드립니다. – anonymous2506
아, 아직 비동기가 아니라면'choices [i] = quizFileReader.ReadLineAsync();를'choices [i] = quizFileReader.ReadLine();으로 변경하고 차단하도록하십시오. Async는 또 다른 짐승이며, 처음 배울 때 걱정할 필요가 없다고 생각합니다. :) –
죄송합니다. 선택 항목을 정의한 다음 for 루프가 스트림을 나눕니다. – anonymous2506