4
22/10/2024 1:59 pm
Topic starter
I need to write a program that, depending on the user’s choice, inputs an integer, double or string variable.
If the variable is int or double, the program increases it by one (+ 1).
If the variable is a string, the program appends "*" at the end (+ "*").
Afterwards, I need to print the result at the console.
I must use switch statement.
Examples:
2 Answers
3
22/10/2024 2:05 pm
Here is my solution with the switch statement (sometimes the best option compared to the if-else statement):
using System; class PlayWithIntDoubleAndString { static void Main() { Console.WriteLine("Please choose your input data type:\n 1 --> int\n 2 --> double\n 3 --> string\n ...and hit ENTER"); int choice = int.Parse(Console.ReadLine()); switch (choice) { case 1: Console.WriteLine("Please enter your INTEGER number: "); int a = int.Parse(Console.ReadLine()); Console.WriteLine("The result is: {0}",(a+1)); break; case 2: Console.WriteLine("Please enter your DOUBLE number: "); double b = double.Parse(Console.ReadLine()); Console.WriteLine("The result is: {0}", (b+1)); break; case 3: Console.WriteLine("Please enter your STRING: "); string c = Console.ReadLine(); Console.WriteLine("The result is: {0}", c + "*"); break; default: Console.WriteLine("Invalid!"); break; } } }
2
22/10/2024 2:09 pm
Here is the same task - solved with if statments:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Task { static void Main() { Console.WriteLine("Please choose a type:\n1 --> int\n2 --> double\n3 --> string"); int choice = int.Parse(Console.ReadLine()); if (choice ==1) { Console.WriteLine("Please enter an integer:"); int inputInt = int.Parse(Console.ReadLine()); inputInt += 1; Console.WriteLine(inputInt); return; } else if (choice ==2) { Console.WriteLine("Please enter a double:"); double inputDbl = double.Parse(Console.ReadLine()); inputDbl += 1; Console.WriteLine(inputDbl); return; } else if (choice==3) { Console.WriteLine("Please enter a string:"); string inputStr = Console.ReadLine(); string addInputStr = inputStr + "*"; Console.WriteLine(addInputStr); return; } }