I'm currently doing a beginner's coding exercise, and have run into a problem. The program I made takes 5 numbers, turns them into an array, and displays the three smallest numbers on the console. I have the input separated into an array, and created a new variable containing the three smallest values, but I'm not sure how to display each number in the array on the console.
I know that's a beginner question, but I've been coding less than a week. I tried searching StackOverflow and found a code to display each integer in a list, but am unsure what to change to display each value in an array.
bool isFive = new bool();
Console.WriteLine("Enter at least 5 numbers, separated by a comma.");
while (!isFive)
{
string text = Console.ReadLine();
string[] result = text.Split(',');
int[] resultInt = result.Select(s => int.Parse(s)).ToArray();
if (resultInt.Length < 5)
{
Console.WriteLine("Invalid list, retry.");
}
else
{
isFive = true;
var smallestThree = resultInt.OrderBy(x => x).Take(3);
????????????????
}
}
Almost there. All you need is string.Join:
Console.WriteLine(string.Join(", ", resultInt.OrderBy(x => x).Take(3)));
Also, instead of using int.Parse have a look at int.TryParse: Select parsed int, if string was parseable to int
Related
Looking for some assistance. I'm sure its really easy, but I just cannot seem to get my head around it.
First, here's my code so far:
//Prompts user to enter numbers
Console.Write("Enter a line of comma-seperated temperatures: ");
string temps = Console.ReadLine();
//Splits commas, seperating numbers into array
string[] numsInString = temps.Split(',');
int temps1 = numsInString.Length;
int[] temps2 = new int[temps1];
for (int i = 0; i < numsInString.Length; i++)
{
temps2[i] = int.Parse(numsInString[i]);
}
Console.WriteLine("Minimum temp: " + temps2.Min());
Console.WriteLine("Average temp: " + temps2.Average());
So, it prompts the user to enter a temperature i.e "5" separated by commas, "5,6,7,8". My trouble is that I cannot have temperatures in the decimal range such as "5.4,5.7,6.3,6.8". I've figured out that I need to convert the string to double, but I'm not entirely sure on how to do that.
Thanks
You want to change the type of your array to double[] and then change your parsing to parse double instead of int:
double[] temps2 = new double[temps1];
for (int i = 0; i < numsInString.Length; i++)
{
temps2[i] = double.Parse(numsInString[i]);
}
As a bit of an aside, you can also use LINQ to express this more declaratively:
double[] temps2 = temps.Split(',')
.Select(double.Parse)
.ToArray();
As already mentioned in other answers and comments you need change int[] array to double[] array and use double.Parse method for parsing strings to double.
But instead of loop or LINQ, I want suggest Array.ConvertAll method which will convert array of string to array of doubles.
Console.Write("Enter a line of comma-seperated temperatures: ");
var rawData = Console.ReadLine();
var rawTemperatures = rawData.Split(',');
var temperatures = Array.ConvertAll<string, double>(rawTemperatures, double.Parse);
Array.ConvertAll method will execute same for loop, but will be tiny tiny (in your case) more effective and enough declarative then LINQ approach
using System;
namespace reverse
{
class Program
{
static void Main(string[] args)
{
int[] a = new int [10];
for (int i= 0; i<a.Length; i++)
{
a[i] = int.Parse(Console.ReadLine());
}
}
}
}
here I can get values from a user by pressing enter key after each time i give the value but I want to give value as a whole with comma. Thanks!
I would suggest to gradually step towards functional programming.
Why?
Weel, with words from Eric Lippert from "Functional programming for beginners"
I will talk about the “why” a little bit, but basically it boils down to
a great many bugs are caused by bad mutations.
By taking a page
from functional style and designing programs so that variables and
data structures change as little as possible, we can eliminate a
large source of bugs.
Structuring programs into small functions
whose outputs each depend solely on inputs
makes for programs that
are easy to unit test.
the ability to pass functions as data
allows us to create new and interesting control flows and patterns,
like LINQ.
Rewriting your code
Use Linq in a single and simple line:
int [] res =
Console.ReadLine () // read the input
.Split (',') // transform it into an array
.Take (10) // consider only the first 10 strings
.Select (int.Parse) // transform them into int
.ToArray (); // and finally get an array
You can add a check after the Split and before Take:
.Where (d => {int t; return int.TryParse (d, out t);}).Take
Try this one and read comments to get more info :
static void Main()
{
string input = Console.ReadLine(); // grab user input in one whole line
string[] splitted = input.Split(','); // split user input by comma sign ( , )
int[] a = new int[splitted.Length]; // create a new array that matches user input values length
for(int i = 0; i < splitted.Length; i++) // iterate through all user input values
{
int temp = -1; // create temporary field to hold result
int.TryParse(splitted[i], out temp); // check if user inpu value can be parsed into int
a[i] = temp; // assign parsed int value
}
}
This method will ensure that program will execute even if user wont input numerics. For example if user input will be :
1 , 2,3,45,8,9898
The output will be :
{ 1, 2, 3, 45, 8, 9898 }
But if the input will be :
1,adsadsa,13,4,6,dsd
The output will be :
{ 1, 0, 13, 4, 6, 0 }
I am learning c# and I encounter problem when attempting to sum the numbers from console input. User inserts numbers separated with commas. Then, they get splitted and at the end they should be parsed to int's for the future calculations as sum.
Here is what I've got:
int[] convertedLine;
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success = int.TryParse(splittedLine[0], out convertedLine);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
on 4th line I get error under convertedLine, that says 'cannot convert from out int[] to out int'.
I will appreciate help that will put me on the right track with my problem.
Thank you.
P
---------- edit ------------
Ok, so I've got this code now and it works. Is there a nicer way to do this parsing for all splitted elements of a string?
int[] convertedLine=new int[3];
string stringLine = System.Console.ReadLine();
string[] splittedLine = stringLine.Split(' ');
var success1 = int.TryParse(splittedLine[0], out convertedLine[0]);
var success2 = int.TryParse(splittedLine[1], out convertedLine[1]);
var success3 = int.TryParse(splittedLine[2], out convertedLine[2]);
System.Console.WriteLine(convertedLine[0] + convertedLine[1] + convertedLine[2]);
System.Console.ReadKey();
You need to initialize the elements of the convertedLine array and then specify the element you want to set to the value you pass to int.TryParse
Your .TryParse should look something like this:
var success = int.TryParse(splittedLine[0], out convertedLine[0]);
Note the [0] next to convertedLine that indicated the element in the int array you are setting
To initialize your convertedLine integer array simply do this line:
int[] convertedLine = new int[x];
Where x is the number of elements you want to have in your array. If you don't want to limit your user to a set amount of inputs you'll have to split on your split character and then initialize your integer array to however many values you found that the user input
The problem is here: int[] convertedLine; and then here: var success = int.TryParse(splittedLine[0], out convertedLine);
You are trying to parse to an array of integers a unique value of integers. Your code is assuming you have multiple integer as inputs
you are trying to convert the string to int in your case you pass an array of int and the function attempt to have an int a parameter.
try this one:
foreach(var i in splittedLine)
{
var success = int.TryParse(splittedLine[i], out convertedLine[i]);
}
The 'out' parameter from your int.TryParse is a single int. You're trying however to put that single int into an array of ints (which you've called 'convertedLine') without specifying where in the array that int should go.
One option then would be to declare your int array with a fixed size (eg)
int[5] convertedLine = new int[5];
which then allows for up to 5 integers. Then where you have
var success = int.TryParse(splittedLine[0], out convertedLine);
you should instead set a fixed value within the array, like this:
int.TryParse(splittedLine[0], out convertedLine[0]);
As an aside you also probably want to try and parse any other ints in the same way, eg:
int.TryParse(splittedLine[1], out convertedLine[1]);
int.TryParse(splittedLine[2], out convertedLine[2]);
This is for a homework assignment which I have been working on for quite a while now but have not been able to figure out. Here are the exact instructions from my teacher if you need them; it is at number five that I am stuck:
(1) Have the user enter a sentence that they want to have encoded.
(2) If the number of characters in the message is odd, concatenate a space (" ") to their message so that our message will always be an even number of letters.
(3) Now create a new char[], call it unCoded where each element is a letter from your secret message.
(4) Now create an empty second char[], call it coded, and define its length equal to the length of the other char[], unCoded.
(5) Now write the values from the uncoded array into the coded array, but flipping each 2 letters.
(6) Then write out the original uncoded message.
(7) Then write out the new coded message.
He also said step 5 must be done in a loop.
Any help would be appreciated, thanks.
What I have so far:
static void Main(string[] args)
{
Console.WriteLine("Enter the sentence you want encoded: ");
string userInput = Console.ReadLine();
int remainder = userInput.Length % 2;
if (remainder!=0)
{
userInput = userInput + " ";
}
char[] unCoded = userInput.ToArray();
char[] coded=unCoded;
//coded.Length = unCoded.Length;
for (int i = 0; i < unCoded.Length; i=i+2)
{
coded[0] = unCoded[1];
coded[1] = unCoded[0];
}
string encoded = new string(coded);
Console.WriteLine("{0}", userInput);
Console.WriteLine("{0}", encoded);
Console.ReadKey();
}
Well, in your loop you don't use the loop parameter, so you just change up the first two values several times. Consider what you are doing in your loop to be the first step of what you actually want to achieve. Do it using the "i" variable and knowing that it's first value is 0. Then when i "grows", the loop will do the same for the next two values.
so just put i in place of 0 and i+1 in place of 1
I am trying to learn C# as I have little experience there. I wanted to set up a Console.Readline in a Do While loop so I can read in an unknown amount of values into an array. It never exits so the comparison in the while is not working. What is wrong?
do
{
line = Console.Read();
if (line != null)
numbers[c++] = line;
numbers = new int[c+1];
} while (line != null);
First of all, I would use a List<int> to save the input values. This avoids the necessity to redimension the array, and you could use the list as a normal array.
Second, there is a lot of difference between the Console.Read and Console.ReadLine. The first returns one by one the character codes of the characters typed and pressing Enter will simply return the character code (13) of the Enter key. To exit the loop you need to press Ctrl + Z that returns -1, not null.
List<int> numbers = new List<int>();
int line;
do
{
line = Console.Read();
if (line != -1)
numbers.Add(line);
} while (line != -1);
for(int x = 0; x < numbers.Count(); x++)
Console.WriteLine(numbers[x]);
However, this is probably not what you really want. If you need to store the numbers typed as real integer numbers you need code like this:
List<int> numbers = new List<int>();
string line = Console.ReadLine();
int number;
do
{
if(int.TryParse(line, out number))
numbers.Add(number);
} while (!string.IsNullOrWhiteSpace(line = Console.ReadLine()));
for(int x = 0; x < numbers.Count(); x++)
Console.WriteLine(numbers[x]);
In this version I get the line input before entering the loop and then continue until the Enter key is pressed. In every loop I try to convert the input to a valid integer number.
Note also the usage of TryParse to convert the string to an integer. If your user types something like "abcdef" the TryParse will return false without throwing an exception.
(Thanks #Patrick for its suggestion.)
If you're using Console.Readline() then line will be null if you press Ctrl+Z (as mentioned by #Patrick). You should check for empty string instead:
do
{
line = Console.ReadLine();
if (line != null)
numbers[c++] = int.Parse(line); //assigning string to the last element in the array of ints?
//if you need to parse string to int, use int.Parse() or Convert.ToInt32()
//whatever suits your needs
numbers = new int[c+1];
} while (!string.IsNullOrEmpty(line));
Anyway, it's not clear what you're trying to accomplish with this code as you're creating new array on every iteration. Moreover, this will not work as you have an array of int but assign a string value to it.