Doing the exercise for The Ultimate C# Series: Part 1 section Working With Text. The solution is as follows, but typing exactly as the solution yields the error code: CS5001: Program does not contain a static ‘Main’ method suitable for an entry point. Can someone suggest a solution? Thank you.
using System;
using System.Collections.Generic;
namespace CSharp1Exercises
{
public class Strings
{
///
/// Write a program and ask the user to enter a few numbers separated by a hyphen. Work out
/// if the numbers are consecutive. For example, if the input is “5-6-7-8-9” or “20-19-18-17-16”,
/// display a message: “Consecutive”; otherwise, display “Not Consecutive”.
///
public void Exercise1()
{
Console.Write("Enter a few numbers (eg 1-2-3-4): ");
var input = Console.ReadLine();
var numbers = new List<int>();
foreach (var number in input.Split('-'))
numbers.Add(Convert.ToInt32(number));
numbers.Sort();
var isConsecutive = true;
for (var i = 1; i < numbers.Count; i++)
{
if (numbers[i] != numbers[i - 1] + 1)
{
isConsecutive = false;
break;
}
}
var message = isConsecutive ? "Consecutive" : "Not Consecutive";
Console.WriteLine(message);
}
Thank you for your response.
I don’t quite follow your suggestion. Can you please copy and paste the entire text with your changes so that I can see exactly where the changes need to go?
Also I clicked on the name of the program in Solution Explorer (can’t double click just single click) but I don’t see anything called Startup project. Is there another place where this setting the String class as Startup project be done.
C#/.NET programs always need a Main() method, which is the method that is called to start your program. So without a Main() method, your program doesn’t start!
Try this:
using System;
using System.Collections.Generic;
namespace CSharp1Exercises
{
public class Program
{
static void Main(string[] args)
{
Strings.Exercise1();
}
}
public class Strings
{
///
/// Write a program and ask the user to enter a few numbers separated by a hyphen. Work out
/// if the numbers are consecutive. For example, if the input is “5-6-7-8-9” or “20-19-18-17-16”,
/// display a message: “Consecutive”; otherwise, display “Not Consecutive”.
///
public static void Exercise1()
{
Console.Write("Enter a few numbers (eg 1-2-3-4): ");
var input = Console.ReadLine();
var numbers = new List<int>();
foreach (var number in input.Split('-'))
numbers.Add(Convert.ToInt32(number));
numbers.Sort();
var isConsecutive = true;
for (var i = 1; i < numbers.Count; i++)
{
if (numbers[i] != numbers[i - 1] + 1)
{
isConsecutive = false;
break;
}
}
var message = isConsecutive ? "Consecutive" : "Not Consecutive";
Console.WriteLine(message);
}
}
}