【问题标题】:reading a text file and multiplying the first line by each of the other lines读取文本文件并将第一行乘以其他每一行
【发布时间】:2016-04-18 01:22:08
【问题描述】:

我正在做这个作业,我需要读取一个整数文本文件,将数字存储到数组中。然后将每行中的数字平方(25之后),然后将平方除以25,然后检查结果是否大于150

我卡住的地方是读取每一行的数字并像我应该的那样在我的方法中使用它们,到目前为止,我的循环和数组打印将每个数字按顺序放入文件中。

非常感谢有关数组部分的任何帮助,谢谢。

这是文本文件:

25   150
60        
63
61
70
72
68
66
68
70

所以,以Math.Pow(60,2) / 25Math.Pow(63,2) / 25 等等为例。然后如果高于 150,则打印“yes”,如果低于 150,则打印“no”

这是我所拥有的: 我还有一门课

class Resistors
{
    //declare variables for the resistance and the volts.
    private  int resistance;
    private int volts;

    public Resistors(int p1, int p2)
    {
        resistance = p2;
        volts = p1;
    }
    //GetPower method.
    //purpose: to get calculate the power dissipation of the resistor.
    //parameters: it takes two intigers.
    //returns: the total power as a double.
    public double GetPower()
    {
        return (Math.Pow(volts, 2) / resistance);

    }
}

剩下的就是这里了。

static void Main(string[] args)

    //declare some variables and an array.
    const int MAX = 50;
    string inputLine = "";
    Resistors[] resistor = new Resistors[MAX];
    //declare a counter and set to zero
    int count = 0;

    // This line of code gets the path to the My Documents Folder
    string environment = System.Environment.GetFolderPath
    (System.Environment.SpecialFolder.Personal) + "\\";
    WriteLine("Resistor Batch Test Analysis Program");
    WriteLine("Data file must be in your Documents folder");
    Write("Please enter the file name: ");
    string input = Console.ReadLine();

    // concatenate the path to the file name
    string path = environment + input;

    // now we can use the full path to get the document
    StreamReader myFile = new StreamReader(path);

    while (inputLine != null)
    {
        inputLine = myFile.ReadLine();
        if (inputLine != null && count < MAX)
        {
            string[] data = inputLine.Split();
            int dataR = int.Parse(data[0]);

            string[] pie = inputLine.Split();
            int pieV = int.Parse(pie[0]);


            resistor[count++] = new Resistors(dataR, pieV);
        }
    }
    WriteLine("Res#\tDissipitation\tPassed");

    for (int j = 0; j < count; j++)
    {

        WriteLine("{0:d}\t{1:N}", j + 1, resistor[j].GetPower());
    }

    ReadKey();
}

【问题讨论】:

    标签: c# arrays split streamreader


    【解决方案1】:

    我认为这应该满足您的需求:

    编辑:

    根据你的cmets,如果你想在第一行读取多个值,你可以用逗号分隔它们,然后拆分。

    25,150
    60        
    63
    61
    70
    72
    68
    66
    68
    70
    

    static void Main(string[] args)
    {            
        // This line of code gets the path to the My Documents Folder
        string environment = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "\\";
        Console.WriteLine("Resistor Batch Test Analysis Program");
        Console.WriteLine("Data file must be in your Documents folder");
        Console.Write("Please enter the file name: ");
    
        string input = Console.ReadLine();
    
        // concatenate the path to the file name
        string path = environment + input;
    
        // Will read all lines
        var lines = File.ReadAllLines(path).ToList();
        // Will get the first line arguments and split them on the comma, you add more arguments if need, just separate them by a comma
        var firstLineArgs = lines[0].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                                    .Select(t => Convert.ToInt32(t))
                                    .ToArray();
        // Will skip the first line arguments and parse all the following numbers
        var numbers = lines.Skip(1)
                           .Select(t => Convert.ToInt32(t))
                           .ToList();
    
        // Will create each Resistors object with the first line arguments (25) and the actual number
        // You can do whatever you want with the second arguments (150)
        var resistors = numbers.Select(t => new Resistors(firstLineArgs[0], t))
                               .ToList();  
    
        Console.WriteLine("Res#\tDissipitation\tPassed");
    
        foreach (var item in resistors)
        {
            // Check if item.GetPower() is greather firstLineArgs[1] (150)
            // I don't know what you want to do if it's greater
            Console.WriteLine("{0:d}\t{1:N}", resistors.IndexOf(item) + 1, item.GetPower());
        }
    
        Console.ReadKey();     
    }
    

    【讨论】:

    • 谢谢,这实际上帮了很多忙,而且大部分时间都有效。如果同一行中 25 旁边有另一个数字,我需要做什么,所以如果我需要除以 25,然后假设加 50。我如何在同一行中读取两个数字。
    • 我根据您的评论和最后一个问题更新更新了我的答案。告诉我是否有帮助。
    【解决方案2】:

    您会发现您编写的代码使用输入文件的第 1 行和第 2 行、第 3 和第 4 行、第 5 和第 6 行调用您的电阻器构造函数...

    您的描述表明您希望保留第一行,然后在构造每个 Resistor 对象时使用它。也许我误解了你的问题。您可能需要考虑显示几个输出点与几个预期输出点。

    您的“inputLine.Split()”也是不必要的。你可以只解析 inputLine 字符串。

    【讨论】:

      【解决方案3】:

      让我从你的代码中提取几行代码:

      if (inputLine != null && count < MAX)
          {
              string[] data = inputLine.Split();
              int dataR = int.Parse(data[0]);
              string[] pie = inputLine.Split();
              int pieV = int.Parse(pie[0]);
          }
      

      你实际上是在用 split(); 做同样的事情。并且Split() 也不是必需的,您可以使用int dataR = int.Parse(inputLine);int pieV = int.Parse(inputLine); 实现相同的目的

      从你在问题中提到的例子

      取 Math.Pow(60,2) / 25 和 Math.Pow(63,2) / 25 等等。

      您必须将文件中的第一个值指定为 resistance 如果是这样(我理解正确),您可以使用以下代码完成整个操作:

      List<string> stringArray = File.ReadAllLines(@"filePath").ToList();
      List<int> intList= stringArray.Select(x => x!=null || x!="" ?0:int.Parse(x)).ToList(); 
      //Now `intList` will be the list of integers, you can process with them;
      int resistance=intArray[0];
      for (int i = 1; i < intArray.Count ; i++)
      {
        resistor[i] = new Resistors(intArray[i], resistance);
      }
      

      您也可以尝试使用您的代码:

      StreamReader myFile = new StreamReader(@"path_here");
      const int MAX = 50;
      string inputLine = "";
      // Resistors[] resistor = new Resistors[MAX];             
      int count = 0;
      int resistance = 0;
      while (inputLine != null)
      {
          inputLine = myFile.ReadLine();
          if (inputLine != null && count < MAX)
          {
              int inputInteger = int.Parse(inputLine);
              if (count == 0) { resistance = inputInteger; }
              resistor[count++] = new Resistors(inputInteger, resistance);
          }
      }
      

      【讨论】:

      • 尽管我是 Pro-Linq 用户,但我认为 OP 可能会觉得它对于单纯的家庭作业来说太复杂了 :)
      • 是的哈哈,感谢所有帮助。这是我的第一堂编程课,它只是编程的基础知识,所以这里的答案中使用的大部分代码都是我们没有涵盖的内容,可能暂时不会涵盖。它确实有很大帮助。谢谢。
      猜你喜欢
      • 1970-01-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2021-07-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多