Question

In: Computer Science

Instead of using int.TryParse, use int.Parse instead and use try/catch in C# to handle possible errors...

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]);
       }
      
   }
}

Solutions

Expert Solution

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


Related Solutions

(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2....
(in C# please.) EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc...
PLease using C# Without using try-catch-throw for exception handling (Ch07), display an error message (using csc or VS2017) when an input is invalid (i.e., no data, wrong format, wrong type, etc.) and fails the type conversion. Generate random integers from any of the following three non-overlapped ranges -14 ~ -7 -2 ~ 5 33 ~ 44 Numbers generated must also randomly distributed across the three ranges.
What is Try and Catch in Java with example?
What is Try and Catch in Java with example?
You are required to use only C for this problem. To begin, instead of using two...
You are required to use only C for this problem. To begin, instead of using two different variables for this problem, you are going to define a structure with two members; one representing the feet and the other one representing the inches. We will also use three functions; one to initialize a structure, one to check the validity of its values, and the last one to print them out. First, define your structure. Next, declare a structure of this type...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define...
*IN JAVA* EXCEPTION HANDLING Concept Summary: 1. Use of try… catch in a program 2. Define an exception class and call it from the driver program. For this lab you will complete two parts. Part (a) of the lab implements try… catch and uses an existing exception in C# or in Java. Write a program that implements an ArrayIndexOutOfBounds error. Part (b) writes a program that converts a time from 24-hour notation to 12-hour notation. Assume the user will enter...
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
Write a try/catch/finally clause to catch one or more specific Exception objects in Java.
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code...
I do not know how to: D. Apply exception handling using try-catch for System.OutOfMemoryException. the code i have in POWERSHELL: while($true) { $input= Read-Host "Enter the option 1-5" if ($input -eq 5) { break } #B. Create a “switch” statement that continues to prompt a user by doing each of the following activities, until a user presses key 5: switch ( $input ){ #Using a regular expression, list files within the Requirements1 folder, with the .log file extension and redirect...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java...
Modify the following program. Add using Exception handing and polymorphism. try-catch block, Finally block in java * description of class Driver here. *these is the main class where it acts like parent class. Compiler will execute firstly static method. import java.util.Scanner; public class Driver {     public static void main (String[] args){         Scanner stdIn = new Scanner(System.in);         String user;         String computer;         char a = 'y';         do {             System.out.println("What kind of Computer would you like?");...
In C++ Use vectors instead of linked lists Create a Hash table program using H(key) =...
In C++ Use vectors instead of linked lists Create a Hash table program using H(key) = key%tablesize with Chaining and Linear probing for a text file that has a list of 50 numbers Ask the user to enter the file name, what the table size is, and which of the two options they want to use between chaining and linear probing
create your own function that wraps it with try catch. Pass in the string to parse,...
create your own function that wraps it with try catch. Pass in the string to parse, and the name of the field, put some logging in the catch How do I do this? say with this code segment? void readStudents() { //Scanner class object declare Scanner readStudentFile = null; //try block begin try { //open file readStudentFile = new Scanner(new File(".\\src\\test\\student.txt")); //loop until end of file while(readStudentFile.hasNextLine()) { String stu = readStudentFile.nextLine(); String[] eachStu; eachStu = stu.split(" "); students.add(new Student(eachStu[0],...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT