如何访问程序循环中的值
本文关键字:循环 程序 何访问 访问 | 更新日期: 2023-09-27 18:35:56
using System;
using System.IO;
namespace FileApplication
{
class Program
{
static void Main(string[] args)
{
String a, b;
int x, y, sum;
string line1, line2;
Console.WriteLine("enter the file name with location :");
a = Console.ReadLine();
Console.WriteLine("enter the second file name with location :");
b = Console.ReadLine();
using (StreamReader sr = new StreamReader(a))
{
while ((line1 = sr.ReadLine()) != null)
{
Console.WriteLine("Value in the first file is :"+line1);
}
}
using (StreamReader sr = new StreamReader(b))
{
while ((line2 = sr.ReadLine()) != null)
{
Console.WriteLine("Value in the second file is :" + line2);
}
}
x = Convert.ToInt32(line1);
y = Convert.ToInt32(line2);
Console.WriteLine("values are :" + line1, line2);
Console.WriteLine("values are :" + x, y);
sum = x + y;
Console.WriteLine("The sum of values in both the file is :" + sum);
Console.ReadKey();
}
}
}
我无法从 while 循环中获取值,以便我可以将它们转换为 int 并进行加法。我该怎么办?
add
x = x + Convert.ToInt32(line1);
在第一个 while 循环中
y = y + Convert.ToInt32(line2);
在第二个 while 循环中
并删除
x = Convert.ToInt32(line1);
y = Convert.ToInt32(line2);
你需要在循环中使用line1
和line2
,它们在循环之外不存在,你的代码甚至不会编译。您需要重构为如下所示的内容:
using (StreamReader sr = new StreamReader(a))
{
while ((line1 = sr.ReadLine()) != null)
{
Console.WriteLine("Value in the first file is :"+line1);
x = Convert.ToInt32(line1);
sum += x;
}
}
using (StreamReader sr = new StreamReader(b))
{
while ((line2 = sr.ReadLine()) != null)
{
Console.WriteLine("Value in the second file is :" + line2);
y = Convert.ToInt32(line2);
sum += y;
}
}
仅供参考:如果字符串中没有数字,Convert.ToInt32(string)
函数将抛出FormatException
。在这种情况下,您需要在try...catch
块中编写此代码。
您可以将读取值的读取和计算放在一个 while 循环中。如果两者的行数相同,则循环将在计算所有总和后终止。否则,您将不得不停止读取您获得 null 的较小文件,并且可以在计算中使用零。
using (StreamReader sr = new StreamReader(a))
using (StreamReader sr = new StreamReader(b))
{
while ((line1 = sr.ReadLine()) != null && (line2 = sr.ReadLine()) != null)
{
Console.WriteLine("Value in the first file is :"+ line1 ?? "null");
Console.WriteLine("Value in the second file is :" + line2 ?? "null");
x = Convert.ToInt32(line1==null ? "0" : line1);
y = Convert.ToInt32(line2==null ? "0" : line2);
Console.WriteLine("values are :" + line1, line2);
Console.WriteLine("values are :" + x, y);
sum = x + y;
Console.WriteLine("The sum of values in both the file is :" + sum);
}