我有一个程序可以根据另一个数组中定义的正确答案对文本文件中的多项选择答案进行分级。这一切都正常,但我想添加显示哪些问题编号不正确的能力,以便用户知道他们出错的地方。下面是我的代码减去任何创建此功能的尝试。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Assignment1_Part_2b
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void exitBtn_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
string[] answers = { "B", "D", "A", "A", "C", "A", "B", "A", "C", "D",
"B", "C", "D", "A", "D", "C", "C", "B", "D", "A" };
string[] studentAnswers = new string[20];
studentAnswers = File.ReadAllLines("StudentAnswers.txt");
int correct = 0;
int incorrect = 0;
int totalMark;
for (int i = 0; i < answers.Length; i++)
{
if (answers[i] == studentAnswers[i])
{
correct = (correct + 1);
}
else
{
incorrect = (incorrect++);
}
totalMark = (correct - incorrect);
wrongAnswerLabel.Text = incorrect.ToString();
correctLabel.Text = correct.ToString();
if (totalMark > 14)
{
resultTextBox.Text = "Pass";
}
else
{
resultTextBox.Text = "Fail";
}
}
}
private void btnClear_Click(object sender, EventArgs e)
{
ClearAll();
}
private void ClearAll()
{
resultTextBox.Text = "";
incorrectLabel.Text = "";
}
}
}
我不知道如何处理这个问题,所以任何帮助都会受到赞赏。
谢谢你们。
答案 0 :(得分:3)
声明另一个列表来存储错误答案的索引:
var wrongAnswers = new List<int>();
然后,如果答案不正确,请将其索引添加到列表中:
else
{
incorrect = (incorrect++);
wrongAnswers.Add(i + 1);
}
顺便说一句,而不是incorrect = (incorrect++);
,你可以使用incorrect++;
另外我想你可能想把这些线移到你的循环之外:
totalMark = (correct - incorrect);
wrongAnswerLabel.Text = incorrect.ToString();
correctLabel.Text = correct.ToString();
if (totalMark > 14)
{
resultTextBox.Text = "Pass";
}
else
{
resultTextBox.Text = "Fail";
}
为了显示错误的答案数字,您可以使用String.Join
并将数字连接到单个string
并显示如下:
string text = string.Join(" ", wrongAnswers);
wrongAnswersLabel.Text = "Wrong answers: " + text;
答案 1 :(得分:2)
您可以使用Linq one-liner:
public int[] WrongAnswers( char[] reference , char[] answer )
{
if ( reference.Length != answer.Length ) throw new ArgumentOutOfRangeException();
int[] wrongAnswers = Enumerable
.Range(0,reference.Length)
.Select( i => new Tuple<int,bool>( i , reference[i]==answer[i] ) )
.Where( x => !x.Item2)
.Select( x => x.Item1 )
.ToArray()
;
return wrongAnswers ;
}
您可以这样做:
public int[] WrongAnswers( char[] reference , char[] answer )
{
if ( reference.Length != answer.Length ) throw new ArgumentOutOfRangeException();
List<int> wrongAnswers = new List<int>() ;
for ( int i = 0 ; i < reference.Length ; +=i )
{
if ( reference[i] != answer[i] ) wrongAnswers.Add(i) ;
}
return wrongAnswers.ToArray() ;
}
答案 2 :(得分:0)
您可以在循环外定义数组或列表,并在错误时添加问题编号。你最终会得到不正确的问题清单。