In: Computer Science
Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
List<int> list = new
List<int>();
Console.WriteLine("Please input
integers: (in one line)");
string input =
Console.ReadLine();
string[] tokens = input.Split(); //
split string into tokens "12 13 10" -> "12" "13" "10"
foreach (string s in tokens)
{
int num;
bool success =
int.TryParse(s,out num); // TryParse returns true if successfully
converted s into an int
// the converted int is put
into the second parameter using keyword "out"
// do you know
why "out" is used here? why not return the converted integer?
if (success)
{
list.Add(num); // add num to list if
success
}
}
Console.WriteLine("Sorted
input:");
list.Sort();
foreach(int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("Sorted input in
reverse:");
for (int
i=list.Count-1;i>=0;i--) {
Console.WriteLine(list[i]);
}
}
}
Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks
//MODIFIED CODE.
using System;
using System.Collections.Generic;
public class Program {
public static void Main() {
List < int > list = new List < int > ();
Console.WriteLine("Please input integers: (in one line)");
string input = Console.ReadLine();
string[] tokens = input.Split(); // split string into tokens "12 13 10" -> "12" "13" "10"
foreach(string s in tokens) {
int num;
//opening try block
try {
//parsing s as integer, will cause exception if s is not int
num = int.Parse(s);
//if no exceptions occurred, simply adding num to list
list.Add(num);
} catch(Exception e) {
//exception occurred, ignoring current token
}
}
Console.WriteLine("Sorted input:");
list.Sort();
foreach(int i in list) {
Console.WriteLine(i);
}
Console.WriteLine("Sorted input in reverse:");
for (int i = list.Count - 1; i >= 0; i--) {
Console.WriteLine(list[i]);
}
}
}
/*OUTPUT*/
Please input integers: (in one line)
a b c 11 -2 3 s 4 -99 100 xyz 7
Sorted input:
-99
-2
3
4
7
11
100
Sorted input in reverse:
100
11
7
4
3
-2
-99