I create two programs and each program has the same task. I create a stack with maximum 10 elements. When You write '+' it means that next, you will insert some number into stack in new line. If the operation is performed successfully program will write line: ':)'. If stack is overflow program will write line: ':('. If You insert '-' it means that program remove last element from the stack and print that element in the console. If stack is empty and you insert '-' program show you ':('.
Example input:
+
1
+
2
+
3
+
4
+
5
+
6
+
7
+
8
+
9
+
0
+
1
-
-
-
-
-
-
-
-
-
-
-
Output:
:)
:)
:)
:)
:)
:)
:)
:)
:)
:(
0
9
8
7
6
5
4
3
2
1
:(
I solved that exercise in two ways; First code: http://ideone.com/WNiNik#comments
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
for (; ; )
{
char sign = char.Parse(Console.ReadLine());
switch (sign)
{
case '+':
{
if (list.Count >= 10) Console.WriteLine(":(");
else
{
int number = int.Parse(Console.ReadLine());
list.Add(number);
}
break;
}
case '-':
{
if (list.Count == 0) Console.WriteLine(":(");
else
{
Console.WriteLine(list[list.Count - 1]);
list.Remove(list[list.Count - 1]);
}
break;
}
}
}
}
}
First code works well on Windows but dont works on ideone.com.
Second code: http://ideone.com/InDjF4
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
List<int> list = new List<int>();
string x;
while (((x = Console.ReadLine())) != null)
{
char sign = char.Parse(x);
switch (sign)
{
case '+':
{
if (list.Count >= 10) Console.WriteLine(":(");
else
{
int number = int.Parse(Console.ReadLine());
list.Add(number);
Console.WriteLine(":)");
}
break;
}
case '-':
{
if (list.Count == 0) Console.WriteLine(":(");
else
{
Console.WriteLine(list[list.Count - 1]);
list.Remove(list[list.Count - 1]);
}
break;
}
}
}
}
}
Second code works well on Windows and ideone.com. I solve that exercise by method of trial and error.Can someone explain me why I get error in my first code and what is the difference between those two codes?
Well this is the problem:
for (; ; )
{
char sign = char.Parse(Console.ReadLine());
...
}
That's going to loop forever - there's nothing in the code to break out of the loop cleanly.
However, Console.ReadLine()
will return null
when it's reached the end of input, at which point you're calling char.Parse(null)
which is throwing the exception.
You need to work out how to end the program cleanly, basically.
You can see exactly the same result on Windows if you put the input into a file (e.g. input.txt
) and then run
Program < input.txt
See more on this question at Stackoverflow