I’m new to programming and I’m trying to write a code that does this:
Entry data
Name 1
Time 1
Name 2
Time 2
Output
Show the name that has the best time.
Now, I’ve managed to create a code that shows the correct result if I write the entry data like this:
A
200
B
300
(numbers are random)
I don’t know how to type into the console the full name (any full word) so I don’t get “String must be exactly one character long”.
I’ve been strugling a bit with this and can’t seem to find the right answer. Thank you!
CodePudding user response:
I think that this should do the trick.
Here is the link so you can try it out.
Console.WriteLine ("Name 1: ");
string name1 = Console.ReadLine(); //put name into a string, so we can use it after
Console.WriteLine ("Time 1: ");
int time1 = Convert.ToInt32(Console.ReadLine()); //put time into an int, so we can see who has better time
Console.WriteLine ("Name 2: ");
string name2 = Console.ReadLine();
Console.WriteLine ("Time 2: ");
int time2 = Convert.ToInt32(Console.ReadLine());
if(time1 > time2) //checking who has better time
Console.WriteLine(name1 " has the better time."); //writing the name with the message
else if(time1 < time2)
Console.WriteLine(name2 " has the better time.");
else
Console.WriteLine(name1 " and " name2 " have the same time");
CodePudding user response:
To read full word you must use Console.ReadLine (Reads the next line of characters
from the standard input stream). To better data representation you need to introduce some class or struct that contains Name
and Time
. I add example according to your input data but if you want to add arbitrary number of elements than it's better to use List instead of array
and do-while loop instead of for loop
public class Sprinter
{
public string Name { get; set; }
public int Time { get; set; }
}
...
//Define array
var results = new Sprinter[2];
// Load data
for (var index = 0; index < results.Length; index )
{
results[index] = new Sprinter();
results[index].Name = Console.ReadLine();
results[index].Time = int.Parse(Console.ReadLine() ?? "0");
}
//Find minimum
var minTime = int.MaxValue;
Sprinter minElement = null;
for (var index = 0; index < results.Length; index )
{
var sprinter = results[index];
if (sprinter.Time < minTime)
{
minElement = sprinter;
minTime = sprinter.Time;
}
}
//Show minimum
Console.WriteLine($"Min is {minElement.Name} with time {minElement.Time}");
Output:
Foo
200
Bar
300
Min is Foo with time 200