Reputation: 33
I've just start C# (with CodeEval) but i've got a little problem with a StringArray when i execute my programme.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeEval
{
class Program
{
public static void fizzBuzz(int x, int y, int n)
{
List<string> list = new List<string>();
int i = 1;
while (i <= n)
{
if (i % x == 0 && i % y != 0)
list.Add("F");
else if (i % x != 0 && i % y == 0)
list.Add("B");
else if (i % x == 0 && i % y == 0)
list.Add("FB");
else
list.Add(i.ToString());
i++;
}
Console.WriteLine(string.Join(" ", list));
}
static int Main(string[] args)
{
try
{
using (StreamReader file = new StreamReader("test1.txt"))
{
while (!file.EndOfStream)
{
string[] line = file.ReadLine().Split(' ');
fizzBuzz(Convert.ToInt32(line[0]), Convert.ToInt32(line[1]), Convert.ToInt32(line[2]));
}
}
}
catch (Exception e)
{
Console.Write("Le fichier ne peut pas être lu: ");
Console.WriteLine(e.Message);
}
Console.ReadLine();
return (0);
}
}
}
My error is in this line
fizzBuzz(Convert.ToInt32(line[0]), Convert.ToInt32(line[1]), Convert.ToInt32(line[2]));
The test1.txt file have this inside :
3 5 10
2 7 15
When i execute the programme, it works for the first line but then he tried the second line : "The input string format is incorrect"
How can it work the first time but not the second ? Need help to understand my problem.
Thanks everybody.
Upvotes: 1
Views: 57
Reputation: 4945
What about do a little guard in your code to block unwanted white spaces.
while (!file.EndOfStream)
{
String line = file.ReadLine();
if (String.IsNullOrWhiteSpace(line))
continue;
string[] tokens = line.Split(new char[] {' '},StringSplitOptions.RemoveEmptyEntries);
fizzBuzz(Convert.ToInt32(tokens[0]), Convert.ToInt32(tokens[1]), Convert.ToInt32(tokens[2]));
}
Upvotes: 1