作者jerry50714 (StarLight)
看板C_Sharp
标题[问题] 并未将物件参考设定为物件的执行个体
时间Sat Mar 26 00:31:54 2011
在下刚开始学C#几周
是要写一个初学者都会碰到的猜数字(nAnB)
本来想说自己可以写出来
不过卡在最後一个点想了两三个小时
也查了许久还是无解
因此来板上请教
以下是部份code(一个for loop内):
string Resp = sr.ReadLine();
if (Resp.Length != 4)
{
sw.WriteLine("Error 3: The number of digit is incorrect.");
}
这个猜数字是用StreamReader读取测值然後把回应用StreamWriter输出的
卡住的这个点是要检测一个error 也就是输入位数不符(非四位数)
但debug的时候就出现了 「并未将物件参考设定为物件的执行个体。」
爬文了一下发现似乎与value不能是null有关
在下自己测了一下觉得应该是因为读取(sr)的关系让Resp.Length出了问题
但碍於自己是初学者实在不懂要如何解决这个问题
到MSDN搜寻到了也是看的很吃力
希望板上前辈指教... 感恩
==========================================================================
小弟还是补一下完整的code 这样可能比较容易找到问题在哪
static void Main(string[] args)
{
StreamReader sr = new StreamReader("file path");
StreamWriter sw = new StreamWriter("file path");
string input = sr.ReadLine();
//读入答案
Int32 Dig4 = Int32.Parse(input) / 1000;
Int32 Dig3 = Int32.Parse(input) % 1000 / 100;
Int32 Dig2 = Int32.Parse(input) % 1000 % 100 / 10;
Int32 Dig1 = Int32.Parse(input) % 1000 % 100 % 10;
//用取余数拆成个、十、百、千位数
int LineCount = 0;
while (sr.Peek() >= 0)
{
sr.ReadLine();
LineCount++;
}
//计算行数
for (int i = 0; i < LineCount; i++)
{
string Resp = sr.ReadLine();
if (Resp.Length != 4)
{
sw.WriteLine("Error 3: The number of digit is incorrect.");
}
//确认读入的测值的位数是否正确(四位数)
else
{
int Res = Int32.Parse(Resp);
int dig4 = Res / 1000;
int dig3 = Res % 1000 / 100;
int dig2 = Res % 1000 % 100 / 10;
int dig1 = Res % 1000 % 100 % 10;
//将测值拆解
if (dig4 == 0)
{
sw.WriteLine("Error 1: The leftmost digit is “0”.");
}
//最左位数不得为0
else if (dig1 == dig2 || dig1 == dig3 || dig1 == dig4 ||
dig2 == dig3 || dig2 == dig4 || dig3 == dig4)
{
sw.WriteLine("Error 2: Digit is re-used.");
}
//输入的四个数字中不得出现重复的数字
//用繁复的土法炼钢写成的nAnB
else
{
int A = 0, B = 0;
if (dig1 == Dig1)
{
A++;
}
if (dig2 == Dig2)
{
A++;
}
if (dig3 == Dig3)
{
A++;
}
if (dig4 == Dig4)
{
A++;
}
if (dig1 == Dig2)
{
B++;
}
if (dig1 == Dig3)
{
B++;
}
if (dig1 == Dig4)
{
B++;
}
if (dig2 == Dig1)
{
B++;
}
if (dig2 == Dig3)
{
B++;
}
if (dig2 == Dig4)
{
B++;
}
if (dig3 == Dig2)
{
B++;
}
if (dig3 == Dig1)
{
B++;
}
if (dig3 == Dig4)
{
B++;
}
if (dig4 == Dig2)
{
B++;
}
if (dig4 == Dig3)
{
B++;
}
if (dig4 == Dig1)
{
B++;
}
sw.WriteLine(A + "A" + B + "B\n");
}
}
}
sw.Close();
Console.ReadLine();
}
不好意思code虽然简单但是很冗长
因为三天前才开始学阵列所以没有使用阵列来写
麻烦各位了._.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 118.231.65.222
※ 编辑: jerry50714 来自: 118.231.65.222 (03/26 01:13)
2F:推 arcred:你算行数时已经把sr读到底了 正式来的时候只会读到null 03/26 03:02
3F:→ jerry50714:原来如此! 没想到这点! 03/26 09:35
4F:→ jerry50714:感谢楼上两j大和a大 多new一个sr总算解决了! 03/26 09:43
5F:→ optimist9266:为看先猜你的input文件最後面有新行字串 03/29 01:39