In: Computer Science
Create C# code that can search a text file and output the data at the line number inputted and amount of entries needed.
Example of call in command window:
Search16s filename.txt 273 10
Where 273 is the line number to start the output from, and 10 is the number of sequences that the program should output.
The number of sequences entered on call should always be a odd number or give an error in console.
The output should also display in the console.
using System;
using System.IO;
class MainClass
{
public static void Main(String[]args)
{
Console.Write("\nEnter the name of the file: ");
string fileName = Console.ReadLine();
if(!File.Exists(fileName))
{
Console.WriteLine("Could not locate file: " + fileName);
}
else
{
string[] allLines = File.ReadAllLines(fileName);
int counter = allLines.Length;
Console.WriteLine("\nFile read complete: Total " + counter + " lines read");
Console.Write("Enter the line number: ");
int lineNum = Int32.Parse(Console.ReadLine());
while(lineNum < 0 || lineNum > counter)
{
Console.WriteLine("Input for line number exceeded the file content!");
Console.Write("\nEnter the line number: ");
lineNum = Int32.Parse(Console.ReadLine());
}
string line = allLines[lineNum - 1];
Console.Write("Enter a sequence number for the line (must be odd): ");
int sequenceNum = Int32.Parse(Console.ReadLine());
while(sequenceNum < 0 || sequenceNum > line.Length)
{
Console.WriteLine("Input for sequence number exceeded the line length");
Console.Write("\nEnter a sequence number for the line (must be odd): ");
sequenceNum = Int32.Parse(Console.ReadLine());
}
while(sequenceNum % 2 == 0)
{
Console.WriteLine("Input for sequence number must be odd");
Console.Write("\nEnter a sequence number for the line (must be odd): ");
sequenceNum = Int32.Parse(Console.ReadLine());
}
string result = line.Substring(0, sequenceNum);
Console.WriteLine("\nResult: " + result);
}
}
}
***************************************************************** SCREENSHOT **********************************************************
INPUT FILE: